Leonardo Lobato Leonardo Lobato - 1 year ago 195
PHP Question

Laravel 5.1 API Enable Cors

I've looked for some ways to enable cors on laravel 5.1 specifically, I have found some libs like:



but none of them has a implementation tutorial specifically to Laravel 5.1, I tried to config but It doesn't work.

If someone already implemented CORS on laravel 5.1 I would be grateful for the help...

Answer Source

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: *");

        $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'));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download