Everyone had a situation when one variable had to be accessible in every view file, for some of us it was $user, for others it was $currentPage or any other case dependent variable. And some of you use Base Controller for that. Let me show you why it’s wrong.
So mostly the problem was solved by making our controller do all the work like this:
class Controller extends BaseController { function __construct() { View::share('user', Auth::user()); View::share('social', Social::all()); } }
This is fine and it works, until you need to add a nice exception error page or 404 page. The problem – these pages don’t reach the Controller at all, so the variables won’t be set. This is a huge and common problem when dealing with bigger applications and error pages which uses the same footer with social media links. (or any other part of the page)
One possible solution – letting the service provider load our global view information. In this way it works even in 404 page:
Open App\Providers\AppServiceProvider and follow these examples*:
class AppServiceProvider extends ServiceProvider { public function boot() { // Using view composer to set following variables globally view()->composer('*',function($view) { $view->with('user', Auth::user()); $view->with('social', Social::all()); }); } }
class AppServiceProvider extends ServiceProvider { public function boot() { // Using view composer for specific view view()->composer('welcome',function($view) { $view->with('user', Auth::user()); $view->with('social', Social::all()); }); } }
That’s it – now these variables are available in every view or just in welcome view file.
*Note: All view composers are resolved via the service container, so you may type-hint any dependencies you need within a composer’s constructor.
For more details and variations you can visit official Laravel documentation
Or you can use shared variables:
view()->share(‘user’, Auth::user());
view()->share(‘social’, Social::all());
[…] the workaround I suggest you take a look at the original article on the Laravel Daily […]
The problem is, that if you want to get data from database and share it, the queries will be duplicated.
how to share variables for controllers?
Sharing variables for the controllers should be done in the base controller at \App\Http\Controllers\Controller.php
and… Is it possible to reach the Auth function here?
Reaching Auth function might require initializing middleware first as of Laravel 5.4
thanks Modestas Vaitkevicius .
this method ( ViewComposer ) better method .