phpauthenticationlaravel-5

Return JSON response instead of 401 Blade file


I am using AuthBasic for API authentication in a Laravel project, I have this problem: when the API request authentication is invalid instead of displaying the JSON response it returns the 401 default blade view template.

Here is the code:

app\Http\Middleware\AuthBasic.php

public function handle($request, Closure $next)
{   
    if (Auth::onceBasic()) {
        return response()->json(["message", "Authentication Required!"], 401);
    } else {
        return $next($request);
    }
}

Solution

  • Found the Solution:

    app\Exceptions\Handler.php

    public function render($request, Exception $exception)
    {   
        if ($request->is('api/*') || $request->wantsJson())
        {
            $json = [
                'success' => false,
                'error' => [
                    'code' => $exception->getCode(),
                    'message' => $exception->getMessage(),
                ],
            ];
            return response()->json($json, 401);
        }
        return parent::render($request, $exception);
    }