Home >Backend Development >PHP Tutorial >How to Enable CORS in Laravel 5.1?
How to Enable CORS in Laravel 5.1
Integrating CORS (Cross-Origin Resource Sharing) into Laravel allows servers to grant permission for cross-origin API calls. This article guides you through specific ways to enable CORS in Laravel version 5.1.
CORS Middleware for Laravel
// app/Http/Middleware/CORS.php namespace App\Http\Middleware; use Closure; class CORS { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { header("Access-Control-Allow-Origin: *"); // ALLOW OPTIONS METHOD $headers = [ 'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE', 'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin' ]; if($request->getMethod() == "OPTIONS") { // The client-side application can set only headers allowed in Access-Control-Allow-Headers return Response::make('OK', 200, $headers); } $response = $next($request); foreach($headers as $key => $value) $response->header($key, $value); return $response; } }
Register the CORS Middleware
After creating the middleware, register it in the app/Http/Kernel.php file:
// app/Http/Kernel.php protected $routeMiddleware = [ //other middlewares 'cors' => 'App\Http\Middleware\CORS', ];
Apply CORS in Routes
Finally, use the cors middleware in the routes where you want to allow cross-origin API calls:
Route::get('example', array('middleware' => 'cors', 'uses' => 'ExampleController@dummy'));
Note for Laravel ^8.0
In Laravel versions 8.0 and above, it's important to use the following syntax to register the CORS middleware due to namespace changes:
// app/Http/Kernel.php protected $routeMiddleware = [ //other middlewares 'cors' => 'App\Http\Middleware\CORS', ]; // routes/web.php or routes/api.php use App\Http\Controllers\ExampleController; Route::get('example', [ExampleController::class, 'dummy'])->middleware('cors');
The above is the detailed content of How to Enable CORS in Laravel 5.1?. For more information, please follow other related articles on the PHP Chinese website!