10
Jan '17

Declaring Instance Variables In Laravel Controllers

Ever found yourself constantly pulling things out of the session to use in controller actions and thinking there must be a better way? Ever tried implementing a constructor to set instance variables but finding them empty? Well I’ve got your back.

The reason that simply populating instance variables in a controller constructor is that the constructor will be run before any middleware is triggered, and hence the session won’t be available to read from, the \Auth::user() won’t be populated etc etc. The way round this is to define a middleware closure in your constructor, which will run after all the other middleware, and ensure that the session etc is available to use here.

This is just a little example to make the current user and site directly available to controller actions. I also tend to put these in shared abstract base controllers for all the other controllers to inherit from, but that’s just me.

protected $active_user;
protected $active_site;

/*
 * Constructor
 */
public function __construct() {
    $this->middleware(function ($request, $next) {
        $this->active_user = \Auth::user();
        $this->active_site = session('site');

        return $next($request);
    });
}

Leave a Reply