1Create a simple middleware called Cors:
2php artisan make:middleware Cors
3
4Add the following code to app/Http/Middleware/Cors.php:
5
6public function handle($request, Closure $next)
7{
8 return $next($request)
9 ->header('Access-Control-Allow-Origin', '*')
10 ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
11 ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Request-With');
12}
13You can replace the * with localhost or keep it as it is.
14
15Next step is to load the middleware. Add the following line to the $routeMiddleware array in app/Http/Kernel.php.
16
17'cors' => \App\Http\Middleware\Cors::class,
18And the final step is to use the middleware on the routes to which you want to set the access origin headers. Assuming you are talking about the new api routes in laravel 5.3, the place to do it is app/Providers/RouteServiceProvider.php, inside the mapApiRoutes() function (you can remove or comment the previous code of the function):
19
20 Route::group([
21 'middleware' => ['api', 'cors'],
22 'namespace' => $this->namespace,
23 'prefix' => 'api',
24 ], function ($router) {
25 //Add you routes here, for example:
26 Route::apiResource('/posts','PostController');
27 });
28
1Step 1: php artisan make:middleware Cors
2
3Step 2: Now open Cors.php from App\Http\Middleware folder and replace handle() function with this code:
4
5public function handle($request, Closure $next)
6{
7 return $next($request)
8 ->header('Access-Control-Allow-Origin', '*')
9 ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
10 ->header('Access-Control-Allow-Headers', 'Content-Type, Authorizations');
11}
12
13Step 3: Lastly, open Kernel.php from App\Http folder add the below line to the $middleware array:
14
15protected $middleware = [
16 ...
17 \App\Http\Middleware\Cors::class,
18];
19
20Now run the application and call API from anywhere.
1Header always set Access-Control-Allow-Origin "*"
2Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
3Header always set Access-Control-Max-Age "1000"
4Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
5
6RewriteEngine On
7RewriteCond %{REQUEST_METHOD} OPTIONS
8RewriteRule ^(.*)$ $1 [R=200,L]
1//I always use an easy method. Just add below lines to \public\index.php file.
2//You don't have to use a middleware I think.
3
4header('Access-Control-Allow-Origin: *');
5header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');