laravel共享变量在控制器中的所有方法 [英] laravel share variable across all methods in a controller

查看:2021
本文介绍了laravel共享变量在控制器中的所有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PHP laravel框架中创建一个简单的网站,其中顶部的导航链接是从数据库动态生成的。我在home控制器动作中生成$ pages变量并传递到布局文件。我的代码如下:

i am making a simple website in PHP laravel framework where the top navigation links are being generated dynamically from the database. I am generating the $pages variable in the home controller action and passing to layout file. My code is as below:

 public function home()
{
    $pages = Page::all();
    return View::make('home')->with('pages', $pages);
}

public function login()
{
    return View::make('login');
}

但是当我尝试访问登录操作时,因为$ pages变量在布局文件中被访问,所以找不到页面。

But when i try to access the login action, i get the error variable $pages not found since the $pages variable is being accessed in layout file. How can i share the same variable across all the actions in a controller?

推荐答案

我通过使用Laravel的视图编辑器解决了这个问题。我做了一个header.blade.php并传递$ pages变量,并添加以下代码到我的routes.php文件。

I solved the problem by using Laravel's view composer. I made a header.blade.php and passed the $pages variable to it and added following code to my routes.php file.

View::composer('header', function($view){
   $pages = Page::all();
   $view->with('pages', $pages);
});   

这篇关于laravel共享变量在控制器中的所有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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