Search

How to enable cors in laravel?

  • Share this:
post-title

Learn what CORS is, how to configure it in Laravel, and the relevant configuration options to expose your application for cross-origin requests securely in laravel.

Have you ever put JavaScript code on a website that was supposed to fetch data from a remote server, only to realize that it didn’t work? Then you probably looked at your browser’s developer tools and noticed an error message referring to CORS or the same-origin policy. 

This article is for you if the remote server is under your control and its server-side code is a Laravel application. To fix your issues, we’ll walk through the process of setting up CORS in Laravel step by step.

What Is CORS?

CORS is a security feature to prevent unauthorized access to server resources. It stands for Cross-Origin Resource Sharing

CORS is a mechanism based on HTTP headers that specify exceptions to the same-origin policy and allow cross-origin requests under specific circumstances. A cross-origin request is a website at one origin, such as https://sample.com, accessing a resource on a different origin, such as https://sample.net. 

Why do we need cors ?

Because it’s a security feature, your default strategy should be to enable CORS only when you’re sure that you need it, and only where you need it. First of all, not every cross-origin request requires CORS. because embedding an image, media file, IFrame, CSS stylesheet, or JavaScript library from another domain isn’t subject to the same-origin policy.

What is required to enable CORS?

The simplest method to enable CORS is to add Access-Control-Allow-Origin:* to the response header from WEB servers, which allows CORS from any source. If you want to limit the source, you should specify the domain in the configuration such as Access-Control-Allow-Origin: https://sample.com. You should note that a domain has to be specified if an http request includes cookie information.

We'll look at two scenarios where you need CORS:

  • Laravel website exposes a clearly defined (REST) API for others. You also expect application programming interface consumers to make API calls directly on their websites through the user’s browser (instead of their servers).
  • Laravel project exposes APIs or other endpoints only for internal use, but website spans multiple domains or subdomains. A particular case of this is when want to access the production back end while developing the front end on localhost or a staging server.

First step create an middleware:

php artisan make:middleware Cors 

Second step edit the 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)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')

    }
}

Third step add the middleware to Kernel.php

protected $routeMiddleware = [
    //......................... 
    'cors'          => \App\Http\Middleware\Cors::class, // added this line only inside $routeMiddleware
	//......................... 
];

Note : cros alias create Kernel.php file and add only 'cors'=> \App\Http\Middleware\Cors::class,

Fourth step now it's time to set it in which we enable cross access

If you want enable globally like api and website both routes and response so you can use code below:

protected $middleware = [
	\App\Http\Middleware\Cors::class, // added this line only inside $middleware 
];

If you want enable only api routes and response so you can use code below:

protected $middlewareGroups = [
     'api' => [
           \App\Http\Middleware\Cors::class, // added this line only inside $middlewareGroups and api alias 
     ],
];

If you want enable only website route routes and response so you can use code below:

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\Cors::class, // added this line only inside $middlewareGroups and api alias 
        ],
    ];

If you want enable only single route and response so you can use code below:

Route::middleware(['cors'])->group(function () {
    Route::post('/page/about', 'Controller@page');
});
About author
Hi ! I'm Adil Khan Ajad from india and i have 8+ years experience in software. i'm working in stack solution as ceo and founder of stackoverlode.
View all posts (3)