Pass variables to multiple view in laravel

落花浮王杯 提交于 2021-02-08 10:13:00

问题


I want to pass a variable to multiple view bu when i use share method in View. Its says the share method isn't find on View.

How you say i use it and i try the composer either but no matter how i try it can't work could you give me simple example of this action

My controller categorycontroller.php

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

My route 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');

what do you suggest?


回答1:


You can make a variable accessible in multiple views using one of these methods for example:

AppServiceProvider ( reference: https://laravel.com/docs/5.6/providers ) with ViewComposer ( reference: https://laravel.com/docs/master/views#view-composers )

You'll need to add to your ServiceProvider boot() method something similar to this:

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

Or inside a controller:

public function __construct() {
  $something = 'just a test';
  View::share('something', $something);
}


来源:https://stackoverflow.com/questions/51845725/pass-variables-to-multiple-view-in-laravel

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