How to make the custom middleware return the specified status code and corresponding information to the ajax request?

just like laravel comes with auth middleware, if it is accessed through web, it will jump to the login page if it is not authenticated. If accessed through ajax, it will return a 401 status code and a json message: {"message": "Unauthenticated."}

Source code of auth middleware:

public function handle($request, Closure $next, ...$guards)
    {
        $this->authenticate($guards);


        return $next($request);
    }

    
protected function authenticate(array $guards)
{
    if (empty($guards)) {
        return $this->auth->authenticate();
    }

    foreach ($guards as $guard) {
        if ($this->auth->guard($guard)->check()) {
            return $this->auth->shouldUse($guard);
        }
    }

    throw new AuthenticationException("Unauthenticated.", $guards);
}

if message is returned by an exception, where is the status code set?

Mar.04,2021

app\ Exceptions\ Handler.php

 /**
     * 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(route('login'));
    }
Menu