Laravel - Send Variable to layout master and keep it during session

元气小坏坏 提交于 2020-01-01 19:36:55

问题


I am wondering if there are any way in laravel to send a variable to the layout master and keep it there while the user is logged in. I know how I can do it, like this

$this->layout->with('catalog.categories', $data);

But the problem of this is that I will have to be sending the variable on all the controllers and through all the class. And to get the variable I will need seven or eight lines of code on top of that.

I will give you an easy example. Imagine I have a messenger center in my web. And I want to show the user all the messages he did not read on the top bar. It has to be on the layout master and stay there until he read the messages. Do I have to pass this variable every single time the user changes the route?


回答1:


Laravel has a nice way to handle issues where a same data is used in all views. View Composer is what you are looking for.

View::composer(array('view1','view2'), function($view)
{
    $view->with('data', 'value');
});

Now data varaible is bound to view1 and view2. That means they it will be available every time you load these views.

Where to place them? You can place your view composers wherever you want as long as Laravel can identify it.

Read docs: View Composer



来源:https://stackoverflow.com/questions/27852637/laravel-send-variable-to-layout-master-and-keep-it-during-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!