Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data to layout in Laravel 5.2 on each request

Hi I am building an application using laravel 5.2 I have a messaging system and I would like to populate some sections in my layout like 'Current Unread Messages Count' and a summary of the last 5 messages.

The way i was gonna go about it is to call a method get the data that I need and then pass the data to the layout and then render the view.

I understand this can be done with a view composer but I have no idea how. Any input would be greatly appreicated. Thanks in advance

like image 597
matpulis Avatar asked Mar 05 '16 13:03

matpulis


Video Answer


1 Answers

Yes, you can do that with a view composer

Let's suppose you have a my_menu.blade.php view file and you want to pass some data to it. In a service provider's boot method do:

//every time the my_menu view is rendered, this callback will be called
View::composer('my_menu', function( $view )
{
    $data = //get your data here

    //pass the data to the view
    $view->with( 'data', $data );
} );

Now, everytime the my_menu view will be rendered, Laravel will call your callback, fetch the data and pass the data to the view. So, in your view file, you can access the data with $data

like image 142
Moppo Avatar answered Oct 14 '22 02:10

Moppo