Laravel solve cors issue

Code Examples, Laravel

Laravel solve cors issue

Create Cors.php file at app/Http/Middleware/Cors.php

<?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 mixed
     */
    public function handle(Request $request, Closure $next)
    {
        return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        ->header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, X-Token-Auth, Authorization');
    }
}

Open app/Http/Kernel.php file and add this in $middleware array and $routeMiddleware array.

protected $middleware = [
    \App\Http\Middleware\Cors::class
];

protected $routeMiddleware = [
    'cors' => \App\Http\Middleware\Cors::class,
];

Close routes in middleware in routes.php

Route::group(['middleware' => ['cors']], function () {

});

click for more Laravel codes read about laravel middlewares