The solution you've started with by creating a Cors middleware is a good approach. However, you need to ensure that the middleware is registered and executed with every HTTP request that requires CORS headers.
Here's how you can adjust your Cors middleware and register it in Laravel 11:
- Update your
Corsmiddleware to include all necessary CORS headers:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return \Illuminate\Http\Response
*/
public function handle(Request $request, Closure $next)
{
$response = $next($request);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, X-Auth-Token, Origin, Authorization');
return $response;
}
}
- Register your
Corsmiddleware inbootstrap/app.php. You can do this by adding it to the global middleware stack or as a route middleware. Here's how you can add it to the global middleware stack:
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use App\Http\Middleware\Cors; // Import your Cors middleware
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
$middleware->validateCsrfTokens(except: [
env('APP_URL') . '/researchjspost'
]);
$middleware->pushMiddleware(Cors::class); // Register Cors middleware
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
By adding the Cors middleware to the global middleware stack, it will be applied to all routes in your application. If you want to apply it only to specific routes, you can instead add it as a route middleware and then use it in your routes or route groups.
Remember to replace the wildcard * in the Access-Control-Allow-Origin header with the specific domain you want to allow if you don't want to allow all origins.
After making these changes, your Laravel 11 application should correctly handle CORS and include the necessary headers in the HTTP response.