DEV Community

Dimitrios Desyllas
Dimitrios Desyllas

Posted on

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

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???

Top comments (3)

Collapse
 
karakhanyans profile image
Serg

Hey, if you want to apply middleware to api routes, you can do following

->withMiddleware(function (Middleware $middleware) {
        $middleware->group('api', [
            // Your middlewares here
         ]);
    })
Enter fullscreen mode Exit fullscreen mode

There are also methods like prependToGroup and appendToGroup which you can use

Collapse
 
pcmagas profile image
Dimitrios Desyllas

This is what I did:
stackoverflow.com/a/78237998/4706711

I also appended some extra Info as well

Collapse
 
karakhanyans profile image
Serg

Yeah, that is also another option! Good that you figured it out ;)