0

I am adding user notifications to my system. To access these notifications for a user, I call an API I have created in another system. So, my IndexController looks something like the following

public function index()
{
    if ($user = Sentinel::getUser()) {
        $notifications = MyAPI::returnNotifications($user->id);
        return view('centaur.dashboard', compact('notifications'));
    }
}

Now to problem with the above is that notifications is now only available on the dashboard view. Within my header view I have something like this

@if($notifications)
    @foreach($notifications as $notification)
        <a class="content" href="#">

            <div class="notification-item">
                <h4 class="item-title">{{ $notification->subject }}</h4>
                <p class="item-info">{{ $notification->body }}</p>
            </div>

        </a>
    @endforeach
@endif

But if I now visit another page besides the dashboard page I get a Undefined variable: notifications error. This is because header is on every page, but I am only passing my notification object to the dashboard page.

Is there any way to make this notification object universally available?

Thanks

UPDATE

if($user = Sentinel::getUser()) {
    view()->composer('*', function ($view) {
        $view->with('notifications', MyAPI::returnNotifications($user->id));
    });
}
katie hudson
  • 2,765
  • 13
  • 50
  • 93
  • Possibly duplicate of: http://stackoverflow.com/questions/29715813/laravel-5-global-blade-view-variable-available-in-all-templates – matiit Sep 13 '16 at 10:56

1 Answers1

1

You can use a view composer. In your App\Providers\AppServiceProvider@boot method add:

view()->composer('*', function ($view) {
    $view->with('notifications', MyAPI::returnNotifications($user->id););
});

Now you'll have the variable $notifications in all of your views. If you want it for specific ones just replace the * with the view name.

thefallen
  • 9,496
  • 2
  • 34
  • 49
  • That looks like the type of solution I need. One question though, how do I get the user to this boot function? Even if I get the current user, it does not seem to like it even if I do what I have updated the OP with. – katie hudson Sep 13 '16 at 11:08