Laravel-将变量发送到布局母版,并在会话期间保留它 [英] Laravel - Send Variable to layout master and keep it during session

查看:61
本文介绍了Laravel-将变量发送到布局母版,并在会话期间保留它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道laravel中是否有任何方法可以将变量发送到布局母版,并在用户登录时将其保留在该位置.我知道我该怎么做,像这样

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.

我给你举个简单的例子.想象一下,我的网站上有一个Messenger中心.我想向用户显示他在顶部栏中没有阅读的所有消息.它必须位于布局母版上并停留在该位置,直到他阅读消息为止.用户每次更改路线时都必须传递此变量吗?

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?

推荐答案

在所有视图中使用相同数据的情况下,Laravel提供了一种很好的方法来处理问题.您正在寻找 View Composer .

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');
});

现在数据变量已绑定到view1和view2.这意味着它们将在您每次加载这些视图时可用.

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

将它们放在哪里?只要Laravel可以识别,您就可以将视图作曲家放置在任意位置.

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

阅读文档: View Composer

这篇关于Laravel-将变量发送到布局母版,并在会话期间保留它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆