5

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

Moppo
  • 18,797
  • 5
  • 65
  • 64
matpulis
  • 123
  • 3
  • 11
  • 1
    Possible duplicate of [Laravel : having the same element on each of my pages](http://stackoverflow.com/questions/35105578/laravel-having-the-same-element-on-each-of-my-pages) – Gal Sisso Mar 05 '16 at 13:37

1 Answers1

7

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

Moppo
  • 18,797
  • 5
  • 65
  • 64
  • 2
    Thank you for the answer. What you said works I actually found a video on laracasts wich explains this very well and even shows you how you can make ServiceProviders to keep this as clean as possible :) https://laracasts.com/series/laravel-5-fundamentals/episodes/25 – matpulis Mar 05 '16 at 13:38