Passing the same data over different views in Laravel

对着背影说爱祢 提交于 2019-12-08 02:20:27

问题


I have for example this code in my HomeController:

    public function index() {


    $comments = Comment::get_recent();
    $top = User::get_top_uploaders()->get();
    $top_something = User::get_top_something_uploaders()->get();
    $data = Post::orderBy('created_at', 'DESC')->paginate(6);

    return View::make('index')  ->with('data', $data)
                                ->with('comments', $comments)
                                ->with('top', $top)
                                ->with('top_something', $top_something);

}

It works great, but I need to make another couple of view with the same data not only for index but also for other pages like comments(), post()... How to make this in HomeController that I don't need to make it copy and paste those variables in every controller?


回答1:


Pass your data using share method:

// for single controller:
class SomeController extends BaseController {
  public function __construct()
  {
    $data = Post::orderBy('created_at', 'DESC')->paginate(6);
    View::share('data', $data);
  } 
}

For all controllers you can put this code in BaseController's constructor




回答2:


If the data is displayed using the same HTML each time you could put that piece of HTML into a partial and then use a View Composer.

Create a view and call it whatever you want and put in your HTML for the data.

In templates that need that partial include it @include('your.partial')

In either app/routes.php or even better app/composers.php (don't forget to autoload it)

View::Composer('your.partial', function($view)
{
    $data = Post::orderBy('created_at', 'DESC')->paginate(6);
    $view->with('data', $data);
});

Now whenever that partial is included in one of your templates it will have access to your data



来源:https://stackoverflow.com/questions/22835002/passing-the-same-data-over-different-views-in-laravel

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