Search code examples
laravelscopemiddlewarelaravel-middleware

laravel middleware within __construct


I'm using https://github.com/appstract/laravel-multisite which is working fine.

Within my controllers methods, I can var_dump current_site() and the correct information is displayed.

My issue is that within my controller __construct method the current_site function returns null i.e the multi_site object hasn't yet been setup.

public function __construct()
{
    //this returns null
    var_dump(current_Site());
}


public function index()
{
    //this works
    var_dump(current_Site());
}

I assuming the constructor is called before the routing has been done and therefore thats the issue, but I wanted to only call the current_site function once and have the controller know which site was being used from the start, so all methods etc would know.

I think this is just a lack of knowledge on my part rather than a code issue...any guidance ?

My route groups as like this

'domain' => 'dealer1.'.config('multisite.host'),
'as' => 'dealer1.',
'middleware' => 'site:dealer1'

I know this is todo with middleware not being done before the __construct being called but should I call it by doing

  $this->middleware('CurrentSite');

wWhat step should I do next?

Edit

I've changed my code to

 public function __construct()
    {



        $this->middleware(function ($request, $next) {
            //this dumps correctly
            var_dump(current_Site() );
               $this->currentSite = current_Site();
            return $next($request);
        });
        //this is null
       //var_dump($this->currentSite);
       //die("here");

    }

Solution

  • You could try something like:

    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            var_dump(current_Site());
    
            return $next($request);
        });
    }
    

    https://laravel.com/docs/master/controllers#controller-middleware

    Hope this helps!