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'));
    }
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b367f1-2bfff.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b367f1-2bfff.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?