From a controller method, I send $notifications
to the home view and display notifications on a header of my website.
The Profile views extend the home view and I also wanted to display the notifications on the profile view.
But it generates an error that undefined variable $notifications when I request for the profile view.
I think one solution is that to send $notifications
when returning profile view from controller method, but in the website, there are many views on which I wanted to show notification tab so it's the right way that I am thinking.
I returned the home view by following way
return view('home')->with(['unseen_notification_counter'=>$unseen_notification_counter,'notifications'=>$notifications]);
here is the code in the home view in the header section
<ul class="dropdown-menu" id="notificationlist">
@foreach($notifications as $notification)
<li>
<a href="{{route('user.profile',$notification->id)}}" class="dropdown-item">
<img src="http://localhost/webproject/public/user_images/{{$notification->image}}" class="img-thumbnil" width="20px" height="20px">
<strong>{{$notification->username}}</strong>
<span style="white-space: initial;">sent you a friend request.</span>
</a>
</li>
@endforeach
</ul>
If you're wanting to pass the same data to multiple views within your application you could use View Composers
E.g. in the boot()
method of your AppServiceProvider you would have something like:
public function boot()
{
view()->composer(['home', 'profile'], function ($view) {
$notifications = \App\Notification::all(); //Change this to the code you would use to get the notifications
$view->with('notifications', $notifications);
});
}
Then you would just add the different blade file names (like you would with a route) to the array.
Alternatively, you could share the notifications with all views:
public function boot()
{
$notifications = \App\Notification::all(); //Change this to the code you would use to get the notifications
view()->share('notifications', $notifications);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With