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.
This target can achieve through different method,
1. Using BaseController
The way I like to set things up, I make a
BaseController
class that extends Laravel’s ownController
, and set up various global things there. All other controllers then extend fromBaseController
rather than Laravel’s Controller.2. Using Filter
If you know for a fact that you want something set up for views on every request throughout the entire application, you can also do it via a filter that runs before the request — this is how I deal with the User object in Laravel.
OR
You can define your own filter
and call it through simple filter calling.
Update According to Version 5.*
3. Using Middleware
Using the
View::share
withmiddleware
4. Using View Composer
View Composer also help to bind specific data to view in different ways. You can directly bind variable to specific view or to all views. For Example you can create your own directory to store your view composer file according to requirement. and these view composer file through Service provide interact with view.
View composer method can use different way, First example can look alike:
You could create an
AppHttpViewComposers
directory.Service Provider
After that, add this provider to config/app.php under "providers" section.
TestViewComposer
ViewName.blade.php
This method could help for only specific View. But if you want trigger ViewComposer to all views, we have to apply this single change to ServiceProvider.
Reference
Laravel Documentation
For Further Clarification Laracast Episode
If still something unclear from my side, let me know.