samedi 16 juin 2018

Laravel 5.6 Changing redirect with unauth with guards

I have an admin and the regular web guard that Laravel 5.6 comes with. As i have seen that Laravel 5.5 up has changed their Exceptions.php file located in \app\Exceptions\Exceptions.php so that the function:

   /**
     * Convert an authentication exception into an unauthenticated response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Auth\AuthenticationException  $exception
     * @return \Illuminate\Http\Response
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        return redirect()->guest('/login');
    }
}

is no longer there. And in order for the

$this->middleware('auth:admin');

to work and redirect to the admin login and not the just "/login" i needed this method to be in this Exception file. I read on here that you could just copy this and use it as the only thing it did was override and Laravel removed it for some reason. But to the point, In order for me to make my switch statement that makes the method look like this:

protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);

            $guard = array_get($exception->guards(), 0);
            switch($guard) {
                case "admin":
                    $login = "admin-login";
                    break;
                default:
                    $login = "login";
                    break;
            }
        }

        return redirect()->guest(route($login));
    }

But when trying to load to see if it redirects to the admin login when going to the /admin/login, it says

Undefined variable: login

What is the issue? I am guessing it has to do something with the $guard, but i am unsure. Any help is greatly appreciated!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire