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?

2
  • i try to use View Share method but it isn't defined in view. Commented Aug 14, 2018 at 18:25
  • What's your Laravel version? Commented Aug 14, 2018 at 19:55

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

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.
What Laravel version are you using? You should use this trait: use Illuminate\Support\Facades\View;
laravel 5.6 version and yet i recive "Method Illuminate\View\View::share does not exist."
View is not Illuminate\View\View it is the facade, always View or Illuminate\Support\Facades\View

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.