Laravel 5.1 API Enable Cors Laravel 5.1 API Enable Cors laravel laravel

Laravel 5.1 API Enable Cors


Here is my CORS middleware:

<?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;    }}

To use CORS middleware you have to register it first in your app\Http\Kernel.php file like this:

protected $routeMiddleware = [        //other middlewares        'cors' => 'App\Http\Middleware\CORS',    ];

Then you can use it in your routes

Route::get('example', array('middleware' => 'cors', 'uses' => 'ExampleController@dummy'));
Edit: In Laravel ^8.0 you have to import the namespace of the controller and use the class like this:
use App\Http\Controllers\ExampleController;Route::get('example', [ExampleController::class, 'dummy'])->middleware('cors');


I always use an easy method. Just add below lines to \public\index.php file. You don't have to use a middleware I think.

header('Access-Control-Allow-Origin: *');  header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');


I am using Laravel 5.4 and unfortunately although the accepted answer seems fine, for preflighted requests (like PUT and DELETE) which will be preceded by an OPTIONS request, specifying the middleware in the $routeMiddleware array (and using that in the routes definition file) will not work unless you define a route handler for OPTIONS as well. This is because without an OPTIONS route Laravel will internally respond to that method without the CORS headers.

So in short either define the middleware in the $middleware array which runs globally for all requests or if you're doing it in $middlewareGroups or $routeMiddleware then also define a route handler for OPTIONS. This can be done like this:

Route::match(['options', 'put'], '/route', function () {    // This will work with the middleware shown in the accepted answer})->middleware('cors');

I also wrote a middleware for the same purpose which looks similar but is larger in size as it tries to be more configurable and handles a bunch of conditions as well:

<?phpnamespace App\Http\Middleware;use Closure;class Cors{    private static $allowedOriginsWhitelist = [      'http://localhost:8000'    ];    // All the headers must be a string    private static $allowedOrigin = '*';    private static $allowedMethods = 'OPTIONS, GET, POST, PUT, PATCH, DELETE';    private static $allowCredentials = 'true';    private static $allowedHeaders = '';    /**     * Handle an incoming request.     *     * @param  \Illuminate\Http\Request  $request     * @param  \Closure  $next     * @return mixed     */    public function handle($request, Closure $next)    {      if (! $this->isCorsRequest($request))      {        return $next($request);      }      static::$allowedOrigin = $this->resolveAllowedOrigin($request);      static::$allowedHeaders = $this->resolveAllowedHeaders($request);      $headers = [        'Access-Control-Allow-Origin'       => static::$allowedOrigin,        'Access-Control-Allow-Methods'      => static::$allowedMethods,        'Access-Control-Allow-Headers'      => static::$allowedHeaders,        'Access-Control-Allow-Credentials'  => static::$allowCredentials,      ];      // For preflighted requests      if ($request->getMethod() === 'OPTIONS')      {        return response('', 200)->withHeaders($headers);      }      $response = $next($request)->withHeaders($headers);      return $response;    }    /**     * Incoming request is a CORS request if the Origin     * header is set and Origin !== Host     *     * @param  \Illuminate\Http\Request  $request     */    private function isCorsRequest($request)    {      $requestHasOrigin = $request->headers->has('Origin');      if ($requestHasOrigin)      {        $origin = $request->headers->get('Origin');        $host = $request->getSchemeAndHttpHost();        if ($origin !== $host)        {          return true;        }      }      return false;    }    /**     * Dynamic resolution of allowed origin since we can't     * pass multiple domains to the header. The appropriate     * domain is set in the Access-Control-Allow-Origin header     * only if it is present in the whitelist.     *     * @param  \Illuminate\Http\Request  $request     */    private function resolveAllowedOrigin($request)    {      $allowedOrigin = static::$allowedOrigin;      // If origin is in our $allowedOriginsWhitelist      // then we send that in Access-Control-Allow-Origin      $origin = $request->headers->get('Origin');      if (in_array($origin, static::$allowedOriginsWhitelist))      {        $allowedOrigin = $origin;      }      return $allowedOrigin;    }    /**     * Take the incoming client request headers     * and return. Will be used to pass in Access-Control-Allow-Headers     *     * @param  \Illuminate\Http\Request  $request     */    private function resolveAllowedHeaders($request)    {      $allowedHeaders = $request->headers->get('Access-Control-Request-Headers');      return $allowedHeaders;    }}

Also written a blog post on this.