The CORS issue in Laravel 10 can be resolved by adding the appropriate headers to the response. You can create a middleware to handle CORS headers and apply it to the routes or globally.
Here's an example of how you can create a middleware to handle CORS headers:
<?php
namespace App\Http\Middleware;
use Closure;
class CorsMiddleware
{
public function handle($request, Closure $next)
{
$response = $next($request);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
return $response;
}
}
To apply this middleware globally, you can add it to the $middleware property in the App\Http\Kernel class:
protected $middleware = [
// ...
\App\Http\Middleware\CorsMiddleware::class,
];
Alternatively, you can apply the middleware to specific routes by adding it to the $routeMiddleware property in the App\Http\Kernel class:
protected $routeMiddleware = [
// ...
'cors' => \App\Http\Middleware\CorsMiddleware::class,
];
Then, you can use the middleware in your routes:
Route::group(['middleware' => 'cors'], function () {
// Your routes here
});
Make sure to clear the cache after adding the middleware by running the following command:
php artisan route:cache
This should resolve the CORS issue and allow requests from any origin.