Laravel.在所有路线中保持可变的视野 [英] Laravel. Keep variable in view during all routes

查看:106
本文介绍了Laravel.在所有路线中保持可变的视野的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在laravel 4.2中遇到了一个非常简单的问题,但我无法解决.我得到了右侧栏,该栏必须包含所有路由期间数据库表中的某些内容.我在首页路由上获取了mysql查询,并传递了变量以查看:

I got pretty simple problem in laravel 4.2 but i can't solve it. I got included right-side-bar which must contain some content from my database table during all routes. I got mysql query on home page route and I pass variable to view:

$query....    
return View::make('home')->with('query', $query);

我想要的是将这个变量发送到包含的视图右侧栏",但是它必须在所有路径中都可以识别它.我尝试嵌套,共享变量,但是由于路线改变,我的右侧栏"视图无法识别变量$ query.我想听听我如何解决的一些建议.预先感谢!

All I want is to send this vatiable to included view 'right-side-bar', but it has to recognize it during all routes. I tried nesting, sharing variable, but since routes change, my 'right-side-bar' view can't recognize variable $query. i would like to hear some suggestions how i can solve it. Thanks in advance!

推荐答案

使用View Composers

请记住,使用View Composer时,您应该通过Composer自动加载文件/类.

Keep in mind that when you are using view composers you should autoload your files/classes via composer.

快速肮脏的方式:

View::composer('your-view-name', function($view)
{
    $query = //your query code
    $view->with('query', $query);
});

或具有多个视图:

View::composer(array('a-view','a-second-view'), function($view)
{
    $query = //your query code
    $view->with('query', $query);
});

基于类的方法(推荐)

View::composer('my-view', 'MyViewComposerClass');

然后创建课程

class MyViewComposerClass{

    public function compose($view)
    {
        $query = //your query code
        $view->with('query', query );
    }

}

使用基本控制器

一个简单的解决方法就是在构造函数内的BaseController中执行类似的操作.

Well an easy fix for what you want is to do something like this in your BaseController inside the constructor.

BaseController.php

public function __construct(){
        $query = //your query code
        View::share('query', $query);
}

然后使您的其他控制器(显然扩展了BaseController) 像这样在其构造函数中构造父控制器

And then make your other controllers(which obviously extend the BaseController) to construct the parent controller in their constructors like this

扩展BaseController.php的其他控制器

public function __construct(){
    parent::__construct();

}

然后像往常一样访问变量.

Then access the variable like you always do.

希望这会有所帮助.

有关视图作曲家的更多信息:

More about view composers :

Laravel 4.2: http://laravel.com/docs/4.2/responses#view -composers

Laravel 4.2: http://laravel.com/docs/4.2/responses#view-composers

Laravel 5.1: http://laravel.com/docs/5.1/views#view -composers

Laravel 5.1: http://laravel.com/docs/5.1/views#view-composers

这篇关于Laravel.在所有路线中保持可变的视野的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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