Why you shouldn't set global variables in Base Controller

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

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 68 courses (1188 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses