How I can prevent the redirections in API using middleware on Laravel 11?

Dimitrios Desyllas - Mar 28 - - Dev Community

I am trying to override the default behaviour of the laravel response if user is unauthenticated:

According to this answer I need to override the default behaviour for my api calls and prevent the redirections regardless the header using a middleware:

namespace App\Http\Middleware
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class ApiMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request):

Laravel 11 does not have a Kernel.php compared to Laravel 10. Therefore solutions such as placing middleware into Kernel.php is not feasible.

But at bootstap/app.php there's:

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();
Enter fullscreen mode Exit fullscreen mode

But how I can apply the middleware at api routes???

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player