0

No idea if i've done this efficiently:

I am trying to load notifications from the database relevant to the Auth::user()->id in the notification table, and display them if they are unread (unread = 0)

I have a script in my app.blade.php: (it collects the array succesfully, but for the var request i want the '1' to be the variale 'id' but i don't know how to grab it correctly, also how do i display the contents of an array via javascript (foreach loop) confused with that (NOTE: i'm happy to swap to AJAX i don't know what would be better for this.

App.blade script

<script>
    $(document).ready(function() {
        $('.dropdown-toggle').on('click', function() {
            $('.menu').html('Loading please wait ...');
            var id = {{ Auth::user()->id }};

            var request = $.get('/notifications/1');
            request.done(function(response) {
              console.log(response);
              $(".menu").html(response);
            });
        });
    });

routes.php

route::get('/notifications/{user_id}', 'NotificationController@get');

NotificationController

public function get($user_id)
{
  $user = User::findOrFail($user_id);
  $notifications = Notification::all();
  // dd($notifications);
  $notification_array = $user->notifications()->where('read', 0)->get();

  return $notification_array;
}
Jake Groves
  • 327
  • 2
  • 4
  • 17

1 Answers1

0

Try this:

var id = "{{ Auth::user()->id }}";
var request = $.get('/notifications/' + id);

Note the quotes around the assignment to id.

Then to loop an array use:

for (var index in myArray) {
    var e = myArray[index];
    // do something with e
}
  • thankyou that helps alot im returning it as an object can i atill use it as an arrayu?? – Jake Groves Mar 14 '16 at 13:40
  • Yes you can access js object properties in a similar fashion. See this answer and the explanation behind hasOwnProperty as well: http://stackoverflow.com/questions/8312459/iterate-through-object-properties –  Mar 14 '16 at 13:44
  • okay thanks i'll try to do that ... arrays seem easier xD thanks alot – Jake Groves Mar 14 '16 at 13:59