在Laravel的不同视图上传递相同的数据 [英] Passing the same data over different views in Laravel
本文介绍了在Laravel的不同视图上传递相同的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有例如在HomeController中的这段代码:
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);
}
它工作得很好,但我需要再做几个( comments()
, post()
... 。
如何在HomeController中做这个,我不需要复制和粘贴这些变量在每个控制器?
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?
推荐答案
使用共享方法传递数据:
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);
}
}
对于所有控制器,您可以将此代码放在BaseController的构造函数中
For all controllers you can put this code in BaseController's constructor
这篇关于在Laravel的不同视图上传递相同的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文