43

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'));
}
4
  • laravel-news.com/custom-exception-reporting i found this
    – Felix
    Jul 27, 2017 at 3:43
  • So you can catch the Authentication Error and then redirect before it gets caught by laravels. Nice thanks
    – Rob
    Jul 27, 2017 at 4:57
  • @robertmylne is it working ? because this solution is just for reporting !!
    – Maraboc
    Jul 27, 2017 at 7:48
  • @Maraboc it's not really doing what I had hoped it do. I was really hoping there was a place to override it.
    – Rob
    Jul 28, 2017 at 1:44

13 Answers 13

70

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 Illuminate\Auth\AuthenticationException;
use Response;

in the Handler file.

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

<?php
    namespace App\Exceptions;
    use Exception;
    use Request;
    use Illuminate\Auth\AuthenticationException;
    use Response;
    use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
    class Handler extends ExceptionHandler
    {
        (...) // The dfault file content
        /**
         * Convert an authentication exception into a response.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Illuminate\Auth\AuthenticationException  $exception
         * @return \Illuminate\Http\Response
         */
         protected function unauthenticated($request, AuthenticationException $exception)
         {
            return $request->expectsJson()
                    ? response()->json(['message' => 'Unauthenticated.'], 401)
                    : redirect()->guest(route('authentication.index'));
    }
}
6
  • 1
    Best answer I've found, thanks! Just one thing: is there a way instead of using expectsJson(), checking if the request was via the api route? Nov 2, 2017 at 22:53
  • you are awesome men, i was thinking on disable the web middleware but this solution is best. Jan 12, 2018 at 13:07
  • 4
    if (in_array('api', \Route::getCurrentRoute()->computedMiddleware)) { return response()->json(['error' => 'Unauthenticated.'], 401); }
    – paing
    Jan 27, 2018 at 20:18
  • unauthenticated function in kernal.php is not present in version 5.7.
    – Ujjual
    Nov 15, 2018 at 13:01
  • thank you so much, but I had to exchange the line response and redirect with each other, as I am having an api, in which i have a logout method, so in postman when i logged out the user after filling the header value like authorization = bearer plus access token generated by login, on first hit it logged out the user but if i clicked again, it says no message , and now its been replaced by json message : unauthenticated Nov 20, 2018 at 5:14
22

Here's how I solved it. In render function I caught exception class. And in case if it's Authentication exception class I wrote my code for redirect (the code I would write in unauthenticated function in previous version).

public function render($request, Exception $exception)
{
    $class = get_class($exception);

    switch($class) {
        case 'Illuminate\Auth\AuthenticationException':
            $guard = array_get($exception->guards(), 0);
            switch ($guard) {
                case 'admin':
                    $login = 'admin.login';
                    break;
                default:
                    $login = 'login';
                    break;
            }

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

    return parent::render($request, $exception);
}
5
  • 2
    thanks it worked for me. i used DevMarketer MultiAuth tutorial in youtube but it seems it's not working in laravel 5.5. this solve my problem. Sep 10, 2017 at 7:02
  • worked with me 2, and i am suing devMarketer...world is too small Nov 11, 2017 at 0:31
  • Working on this same issue. When you got this to work, did you use the stock Laravel 5.5 function for unauthenticated? Or did you also include the version of the unauthenticated function from 5.4?
    – cmpreshn
    Jul 4, 2018 at 1:44
  • Have tried this code, but $exception->guards() always returns nothing for me, so I have nothing to test against. If you have any additional resources you could recommend for a solution, it would be appreciated. Thanks for your answer.
    – cmpreshn
    Jul 4, 2018 at 1:55
  • it still gives me this Route [login] not defined. Jun 27, 2019 at 9:16
7

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.

We need to just include the use Illuminate\Auth\AuthenticationException;

and then it works as in laravel 5.4

1
  • Thanks, this solution is work for me in Laravel 5.5 :)
    – Tommy Tom
    Nov 9, 2017 at 2:23
5

For Laravel ( 5.4, 6, 7, 8.x )

I don't want to change in the vendor directory encase it gets overridden by composer updates. You can just override it as you did in 5.4. Just make sure to include.

File: App\Exceptions\Handler.php

Copy this below code and past to your app\Exception\Handler

<?php

namespace App\Exceptions;

use Request;
use Illuminate\Auth\AuthenticationException;
use Response;

use Illuminate\Support\Arr;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Throwable  $exception
     * @return void
     *
     * @throws \Exception
     */
    public function report(Throwable $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $exception
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws \Throwable
     */
    public function render($request, Throwable $exception)
    {
        return parent::render($request, $exception);
    }
        protected function unauthenticated($request, AuthenticationException $exception)
    {
        // return $request->expectsJson()
        //             ? response()->json(['message' => $exception->getMessage()], 401)
        //             : redirect()->guest(route('login'));

        if($request->expectsJson()) {
            return response()->json(['message' =>  $exception->getMessage()],401);
        }

        $guard = Arr::get($exception->guards(), 0);

        switch ($guard) {
            case 'admin':
            $login = 'admin.login';
            break;
            case 'vendor':
            $login = 'vendor.login';
            break;
            
            default:
            $login = 'login';
            break;
        }

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

    }
}

1
  • Worked like a charm in 8.29.0. Thank you. Mar 14, 2021 at 20:54
2

The standard exception handler uses a named route.

So, you just define your route to use that name.

So, in your routes/web.php file, just add the line:

Route::get('mylogin', 'MyLoginController@showLoginForm')->name('login');

The name('login') bit gives this route a name, so the unauthenticated exception will use this route.

You don't need to bother messing around making your own exception handler, or modifying the standard exception handler.

The named routes used by the boilerplate 'auth' code can be found in the vendor/laravel/framework/src/Illuminate/Routing/Router.php file, in the auth() function. (login, logout, register, password.request, password.email and password.reset). These routes are added when you use the Route::auth(); line in the route file.

2
  • Thanks for a simple solution to the problem, I don't know why nobody else has upvoted this, this solved the issue for me, and the complex answers actually didn't even work at all. Jun 26, 2018 at 20:57
  • This helped me alot Sep 26, 2018 at 8:27
1

In newer versions of Laravel, you should go to

app/Http/Middleware/Authenticate.php

Now you can edit the function and redirect it to wherever you want:

protected function redirectTo($request)
{
    if (! $request->expectsJson()) {
        return route('login');
    }
}

Hope it helps.

0

Just add a route for login in routes file:

Route::get('/login', [
   'uses' => 'UserController@getSignin',
   'as' => 'login'
]);
0

Replace Your app\Exceptions\Handler.php code with the following....

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.`enter code here`
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }

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


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

            default:
                $login = 'login';
                break;
        }

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

Copy this to your app\Exception\Handler

use Request;
use Illuminate\Auth\AuthenticationException;
use Response;

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

  $guard = array_get($exception->guards(),0);

  switch ($guard) {
    case 'admin':
        return redirect()->guest(route('admin.login'));
       break;

     default:
       return redirect()->guest(route('login'));
      break;
  }
}
0

For Laravel 7.x+

===========**top add class:**================
use Illuminate\Auth\AuthenticationException;

use Illuminate\Support\Arr;
=======================================

public function render($request, Throwable $exception)
    {
        if($exception instanceof AuthenticationException){
            $guard = Arr::get($exception->guards(), 0);
            switch($guard){
                case 'admin':
                    return redirect(route('admin.login'));
                    break;
                default:
                    return redirect(route('login'));
                    break;
            }
        }

        return parent::render($request, $exception);
    }
0

For Laravel verison 7.*

File: App\Exceptions\Handler.php

use Illuminate\Support\Arr; //Top Class

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

public function render($request, Throwable $exception) {

    // for Multi AUth guard

    if($exception instanceof AuthenticationException){
        $guard = Arr::get($exception->guards(), 0);
        switch($guard){
            case 'admin':
                return redirect(route('admin.login'));
                break;
            default:
                return redirect(route('login'));
                break;
        }
    }



    return parent::render($request, $exception);
}
-1

Other than overriding, you could directly make changes in Handler.php to the existing function unauthenticated located at vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php to redirect to intended route based on guards.

/**
 * Convert an authentication exception into a response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Illuminate\Auth\AuthenticationException  $exception
 * @return \Illuminate\Http\Response
 */
protected function unauthenticated($request, AuthenticationException $exception)
{


    $guard = array_get($exception->guards(),0);
    switch ($guard) {
        case 'admin':
            return $request->expectsJson()
                        ? response()->json(['message' => $exception->getMessage()], 401)
                        : redirect()->guest(route('admin.login'));
            break;

        default:
            return $request->expectsJson()
                        ? response()->json(['message' => $exception->getMessage()], 401)
                        : redirect()->guest(route('login'));
            break;
    }
}
2
  • I'm working on a multiple authentication system, and I've been trying to get this to work, but when this exception is thrown, $exception->guards() is coming back as empty for me. Do you know of any reason why the guards would not be available? I'm working in Laravel 5.5.40, and have been trying to implement multiple guards for authenticating different users. I'm working off of the video series on 'Multi-Auth' by devmarketer.
    – cmpreshn
    Jul 4, 2018 at 1:40
  • making changes in the vendor folder directly is highly bad practice! you should never ever do this
    – Shehzad
    Jan 7, 2019 at 6:46
-14

1.Go to vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php file.

2.Search the method name is unauthenticated.

3.And change the redirect url from redirect()->guest(route('login')) to redirect()->guest(route('api/login')) //whatever you want.

You could return the response as a JSON if it is API services.

7
  • 4
    It is very bad practice to make changes in files from external packages! Don't do this.
    – thephper
    Jan 5, 2018 at 14:38
  • 1
    to ellaborate on @thephper's answer: if you make changes to external packages they will be lost if you ever update them.
    – Andrei C
    Apr 16, 2018 at 13:03
  • If you want to lose all of your code by running a composer update command, use this!!
    – Erfun
    Jul 24, 2018 at 17:34
  • Nothing will impact if you are running the composer update command. In laravel, they are having certain level of security while accessing the API or Routes services. Jul 25, 2018 at 18:04
  • medium.com/@shyammakwana/…
    – San
    Dec 24, 2018 at 5:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.