Califer
Califer

Reputation: 528

How to add an unauthenticated check to the handler in Laravel 5.5?

I modified app/Exceptions/Handler.php to have an unauthenticated function. Since it's purely an API I am only returning json.

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

After adding that php artisan tinker gives me the following error.

[ErrorException]
  Declaration of App\Exceptions\Handler::unauthenticated($request, App\Exceptions\AuthenticationException $exception) should be compatible with Illuminate\Foundation\Exceptions\Handler::unauthenticated($request, Illuminate\Auth\AuthenticationException $exception)

But I'm not sure what needs to change in order for it to be compatible. I idi add a use statement use Illuminate\Auth\AuthentificationException; to the top of the handler.

Upvotes: 1

Views: 1758

Answers (1)

Mohammad Fanni
Mohammad Fanni

Reputation: 4173

you should use Exception and request too

be sure you include like this:

namespace App\Exceptions;

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

and your method should be like this:

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

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

your code just response as json

Upvotes: 1

Related Questions