1

当我在视图中使用共享方法时,我想将一个变量传递给多个视图。它说在 View 上找不到 share 方法。

你怎么说我使用它,我也尝试作曲家,但无论我如何尝试它都无法工作,你能给我这个动作的简单例子吗

我的控制器categorycontroller.php

public function site(){
    $data =  array();
    $data['subcategories']  =  SubCategory::all();
    $data['categories']     =  Category::all();
    return view('template.sitemap',compact("data"));
}

我的路线web.php

Route::get('/404.html', function () {
    return view('template/404');
})->name('404.html');

Route::get('404.html','CategoryController@site')->name('404');

Route::get('/sitemap.html', function () {
    return view('template/sitemap');
})->name('sitemap.html');

Route::get('sitemap.html','CategoryController@site')->name('sitemap');

你有什么建议?

4

1 回答 1

2

您可以使用以下方法之一使变量在多个视图中可访问,例如:

AppServiceProvider(参考:https : //laravel.com/docs/5.6/providers)和 ViewComposer(参考:https ://laravel.com/docs/master/views#view-composers )

您需要在 ServiceProvider boot() 方法中添加类似于以下内容的内容:

public function boot()
{
    View::share('variable_name', 'some_value_here');
}

或在控制器内部:

public function __construct() {
  $something = 'just a test';
  View::share('something', $something);
}
于 2018-08-14T16:48:55.060 回答