I want to have some default data accessible in all views in my Laravel 5 application.
I have tried to search for it but only find results for Laravel 4. I have read the documentation 'Sharing Data With All Views' here but I can't understand what to do. Where should the following code be placed?
View::share('data', [1, 2, 3]);
Thanks for your help.
The documentation is hear https://laravel.com/docs/5.4/views#view-composers but i will break it down 1.Look for the directory Providers in your root directory and create the for ComposerServiceProvider.php with content
I found this to be the easiest one. Create a new provider and user the
'*'
wildcard to attach it to all views. Works in 5.3 as well :-)You can either create your own service provider (
ViewServiceProvider
name is common) or you can use the existingAppServiceProvider
.In your selected provider, put your code in the boot method.
This will make a
$data
variable accessible in all your views.If you rather want to use the facade instead of the helper, change
view()->
toView::
but don't forget to haveuse View;
at the top of your file.The documentation is hear https://laravel.com/docs/5.4/views#view-composers but i will break it down
Look for the directory app\Providers in the root directory of your application and create the file ComposerServiceProvider.php and copy and past the text below into it and save it.
From the root of your application open Config/app.php and look for the Providers section in the file and copy and past this 'App\Providers\ComposerServiceProvider', to the array.
By doing this, we have created the Composer Service Provider. When you run your application with the view Profile like so http://yourdomain/something/profile, the service provider ComposerServiceProvider is called and the class App\Http\ViewComposers\ProfileComposer is instantiated calling the method Composer due to the code below inside the boot method or function.
Go to the directory path app/Http
Create the directory called ViewComposers
Create the file ProfileComposer.php.
Now go to your view or in this case Profile.blade.php and add
and that will show the count of users on the profile page.
To show the count on all pages change
To