Search code examples
laravellaravel-routinglaravel-bladelaravel-views

Pass variables to multiple view in laravel


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?


Solution

  • 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);
    }