Laravel. Keep variable in view during all routes

ぃ、小莉子 提交于 2020-01-25 04:05:28

问题


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

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!


回答1:


EDIT:

Using View Composers

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

The fast dirty way:

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

or with multiple views:

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

The class based approach (recommended)

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

then create the class

class MyViewComposerClass{

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

}

Using the Base Controller

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

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

Other Controller that extends BaseController.php

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

}

Then access the variable like you always do.

Hope this helps..

More about 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



来源:https://stackoverflow.com/questions/29078435/laravel-keep-variable-in-view-during-all-routes

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