Search code examples
phplaravellaravel-5laravel-5.3

Laravel 5.3 correct initialize of the guard in middleware?


I try to make a custom middleware for authentication, everything is correct but not $guard, how can I initizalize it correctly?

My code looks like:

Auth::guard($guard)->guest()

I tried to initialize guard with following methods, but all this is not correct:

1. protected $guard = null;
2.     public function __construct($guard)
    {
        $guard = null;
    }
3.     public function __construct($guard)
    {
        protected = $guard;
    }

But I get there this error message:

Undefined variable: guard

What I do wrong here?


Solution

  • The way to define Guards to your controllers:

    use Illuminate\Support\Facades\Auth;
    
    protected function guard()
    {
        return Auth::guard('guard-name');
    }