1

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?

Ferrmolina
  • 2,737
  • 2
  • 30
  • 46

1 Answers1

2

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);
}
mad4n7
  • 171
  • 7
  • i try to do things you say but i got this error before i even ran the project > php artisan serve In Macroable.php line 75: Method Illuminate\View\View::share does not exist. – mahdi darvishiyan Aug 14 '18 at 18:22
  • What Laravel version are you using? You should use this trait: use Illuminate\Support\Facades\View; – mad4n7 Aug 14 '18 at 20:02
  • laravel 5.6 version and yet i recive "Method Illuminate\View\View::share does not exist." – mahdi darvishiyan Aug 14 '18 at 21:19
  • `View` is not `Illuminate\View\View` it is the facade, always `View` or `Illuminate\Support\Facades\View` – lagbox Aug 15 '18 at 07:09