laravel 在视图之间共享变量

laravel sharing variable between views

考虑这条路线:

Route::get('/', function()
{
    $categories = Category::all()->toHierarchy();

    $stats = array(
        'total_users' => User::all()->count(),
        'total_services' => 5,
        'total_orders' => 2,
        'latest_service' => '1 hour ago'
    );

    return View::make('homepage')
                                ->with('categories', $categories)
                                ->with('stats', $stats);
});

但我需要所有视图中的 $categories 和 $stats!我不想在每个视图或控制器中重复数据库调用,我将如何实现它?

您正在寻找 View Composers。它们允许您在呈现特定视图(或通过 * 的所有视图)时 运行 一些代码。

View::composer('*', function($view){
    $categories = Category::all()->toHierarchy();

    $stats = array(
        'total_users' => User::all()->count(),
        'total_services' => 5,
        'total_orders' => 2,
        'latest_service' => '1 hour ago'
    );
    $view->with('categories', $categories)
         ->with('stats', $stats);
}

您可以将此代码放入 app/filters.php 或创建一个新文件 app/composers.php 并通过在 app/start/global.php[=17= 末尾添加 require app_path().'/composers.php'; 来包含它]

你可以使用简单的:

View::share('data', $data);
View::make....

用于将变量传递给所有视图。