Skip to content

How to handle CORS in Laravel 5

Last updated on February 17, 2018

CORS stands for Cross-Origin Resource Sharing. Origin policy allows only the same origins to share data and this policy will prevent Cross-site Request Forgery attacks. So to enable sharing resources between different origins we use CORS mechanism by setting a special header. By adding a specific origin in the header, you are allowing only those origins to load resources from the API server.

When you try to make an XHR request to API server. If you will get the following message in your browser’s console, it means that you need to enable CORS between the origins.
"XMLHttpRequest cannot load http://192.168.1.67/projects. NO 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost/' is therefore not allowed access. The response had HTTP status code 500."

Here I am going to show you handling CORS in Laravel 5. You can use this technique on any other framework.

By setting header('Access-Control-Allow-Origin: *'); header in the API responses you can allow any origin to access the resources API. But it is not recommended as it is not secure.

There is another header called Access-Control-Allow-Methods basically by using this header we can limit the communication methods. for example following header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE"); header will only allow mentioned methods.

In order to apply this technique in laravel 5, we are going to use Middlewares. So let’s create a middleware called “Cors”.

Using your Terminal or command prompt, navigate to your project’s root directory and run the following artisan command:

 php artisan make:middleware Cors

Above command will create a middleware file in /app/Http/Middleware, using your editor open the file and add below code in it.

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

Now go to /app/Http/Kernel.php and update it by adding the following 'cors' => \App\Http\Middleware\Cors::class,. which will make Laravel aware of your custom middleware:

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'cors' => \App\Http\Middleware\Cors::class, // <<< add this line
];

That is it. Our custom CORS middleware is ready to use. You can use this middleware just like other middlewares.

  Route::get('projects', ['middleware' => 'cors','uses' => 'ProjectController@list']);

You can also use with Route groups -

Route::group(['prefix' => 'api/v1','middleware' => 'cors'], function() {
 Route::get('projects', ['uses' => 'ProjectController@list']);
});

If you want to allow api access to a specific domain, instead of "*" you can use domain name:

header('Access-Control-Allow-Origin: http://domainName.com');
// multiple domains 
header('Access-Control-Allow-Origin: http://domainName.com, http://domainName1.com, http://domainName2.com');

On Apache, you can do this in an httpd.conf section or .htaccess file using mod_headers and this syntax:

Header add Access-Control-Allow-Origin "http://domainName.com"
Header add Access-Control-Allow-Origin "http://domainName1.com"
Header add Access-Control-Allow-Origin "http://domainName2.com"
0 0 votes
Article Rating
Subscribe
Notify of
guest

6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments