Enabling CORS in Laravel 5.1
To enable Cross-Origin Resource Sharing (CORS) in Laravel 5.1, you can utilize middleware. Here's a comprehensive guide to implementing CORS using a custom middleware:
Create a file CORS.php in the app/Http/Middleware directory. Add the following code to this file:
<?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; } }
In your app/Http/Kernel.php file, add the following code to the $routeMiddleware array:
'cors' => \App\Http\Middleware\CORS::class,
Now you can use the cors middleware in your routes. For example:
Route::get('example', ['middleware' => 'cors', 'uses' => 'ExampleController@dummy']);
By adding these changes, you'll enable CORS for the specified routes and allow cross-origin requests from any domain.
The above is the detailed content of How to Enable CORS in Laravel 5.1 Using Middleware?. For more information, please follow other related articles on the PHP Chinese website!