gpt4 book ai didi

laravel - 在 Laravel 中的不同 View 上传递相同的数据

转载 作者:行者123 更新时间:2023-12-02 21:28:40 25 4
gpt4 key购买 nike

例如,我的 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);

}

效果很好,但我需要使用相同的数据创建另外几个 View ,不仅用于索引,还用于其他页面,例如 comments()post()...如何在 HomeController 中做到这一点,我不需要将这些变量复制并粘贴到每个 Controller 中?

最佳答案

使用共享方法传递您的数据:

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

对于所有 Controller ,您可以将此代码放入 BaseController 的构造函数中

关于laravel - 在 Laravel 中的不同 View 上传递相同的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22835002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com