Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

php - Laravel 5.5 change unauthenticated login redirect url

In Laravel < 5.5 I could change this file app/Exceptions/Handler to change the unauthenticated user redirect url:

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

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

But in Laravel 5.5 this has been moved to this location vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php so how can I change it now? I don't want to change stuff in the vendor directory encase it gets overridden by composer updates.

protected function unauthenticated($request, AuthenticationException $exception)
{
    return $request->expectsJson()
                ? response()->json(['message' => 'Unauthenticated.'], 401)
                : redirect()->guest(route('login'));
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

But in Laravel 5.5 this has been moved to this location vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php so how can I change it now? I don't want to change stuff in the vendor directory encase it gets overridden by composer updates.

It's just the case that the function is not there by default anymore.

You can just override it as you did in 5.4. Just make sure to include

use Exception;
use Request;
use IlluminateAuthAuthenticationException;
use Response;

in the Handler file.

For Example my app/Exceptions/Handler.php looks somewhat like this:

<?php
    namespace AppExceptions;
    use Exception;
    use Request;
    use IlluminateAuthAuthenticationException;
    use Response;
    use IlluminateFoundationExceptionsHandler as ExceptionHandler;
    class Handler extends ExceptionHandler
    {
        (...) // The dfault file content
        /**
         * Convert an authentication exception into a response.
         *
         * @param  IlluminateHttpRequest  $request
         * @param  IlluminateAuthAuthenticationException  $exception
         * @return IlluminateHttpResponse
         */
         protected function unauthenticated($request, AuthenticationException $exception)
         {
            return $request->expectsJson()
                    ? response()->json(['message' => 'Unauthenticated.'], 401)
                    : redirect()->guest(route('authentication.index'));
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...