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();
But how I can apply the middleware at api
routes???
Top comments (3)
Hey, if you want to apply middleware to
api
routes, you can do followingThere are also methods like prependToGroup and appendToGroup which you can use
This is what I did:
stackoverflow.com/a/78237998/4706711
I also appended some extra Info as well
Yeah, that is also another option! Good that you figured it out ;)