Enable CORS in Laravel

Tram Ho

CORS is a mechanism that uses the addition of HTTP headers to tell the browser whether an application can access resources of another web application that is not in the same domain. In other words, a web application is called a cross-origin HTTP request when it can retrieve resources on another origin (domain, protocal or porrt) from itself.

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.

The meaning of CORS

As you know the same-origin policy is a privacy policy that all present programs adhere to. This policy helps prevent unauthorized access to resources from other domains for malicious purposes.

Let’s imagine a scenario like this:

Same-origin policy was created to prevent such scenarios to protect users, making it safer to surf the web. If you attempt to access unauthorized data, you will receive an error as shown below

However, in practice there are problems that you need to allow to access resources from another domain. For example, you have a user.example.com site where users register and log in, the second site is blog.example.com is a blog site that users need to log in to read the contents of the blog site. this. Also, you don’t want to have to build two places to store user information. To solve this problem, you need to allow the second site to know the login status of the first site. This article I will introduce you to the steps to do this on a Laravel website.

Install CORS on Laravel

Site server part


I will configure an api url to perform login checking:

This is just a regular route setup. Here I add a ‘validate_api_token’ middleware, this middleware works to validate the token that comes from the blog site, you need this token to confirm that it is generated from a secret key and an algorithm that both parties already know, Other sites cannot get this token, which increases security. You can use any encryption algorithm to generate tokens. I will not go into details on this.


In the controller, we need to write a function to return the login state and some other user information. Yes you can see the code as below:

In the getLoginStatus function, I simply get the user information from laravel’s heppler auth()->user() , if this object is not null then it means that the login is in reverse. I will return the json data type so that I can call them in the ajax function,


The most noticeable part is here. You need to set up a response to tell the browser which domain allows the application, which method and how to access user.example.com site resources . To do that I created a middleware as shown below

I will explain each component to you:

  • Access-Control-Allow-Origin : This setting indicates which sites are allowed to access CORS, the value here can be a string, an array. If an array you set to header('Access-Control-Allow-Origin', ['http://blog.example.com', ;'']) . As you can see, we can specify a local address for CORS.
  • Access-Control-Allow-Methods : Specifies which HTTP Methods are allowed to execute. * means all methods. You can specify specific methods that the application allows, for example, GET, POST, PUT, HEAD, etc.
  • Access-Control-Allow-Credentials : This configuration tells the browser whether or not it can attach the user.example.com site’s cookies in the blog.example.com site’s Cors requests. Note that this header only works if the client also sets the value withCredentials = true
  • Access-Control-Allow-Headers : Allows any header to be attached to CORS requests. Because the laravel application will request a csrf_token with a POST request, so we set the X-CSRF-Token


I will set the middleware just created above in the middleware group in Kernel.php. When you set up middleware in this group, all reuquestments allow CORS

If you don’t want that, you can configure only the url that allows CORS. You will configure the middleware in the routeMiddlewares in the Kernel

Also reset the route as follows:

Ok, got it server api part ( user.example.com ) is done. Next, we need to make a request on the client side ( blog.example.com )

On the client site


We create a simple button to check the login status:

Check CORS site server

To know if the site server allows CORS or not, issue the following command:

The request does not make a direct request to check the login state but rather a preflight. This means it will send a request to check if the server allows CORS. If so, the server will return a response containing the following components:

Otherwise, you will not be able to perform a CORS with the POST method above.

Create an ajax request

I created a simple jquery ajax request like this:

As you can see, it is just a function familiar to us, the only configuration that needs attention is xhrFields: { withCredentials: true } . With this configuration, our request will include the site’s user.example.com cookie in the option. We all know the login status of the site is set by the session and the cookie and only when we send this cookie will the user be able to login. However, for this setting to work, the server side needs to set the header('Access-Control-Allow-Credentials', 'true') , otherwise it will not make sense. Note, the cookie in this case is a third-party cookie and the storage and access of cookies are still strictly in accordance with the same-origin policy . Therefore, we cannot access cookies with document.cookie . It is fully handled automatically by the browser.

After executing the above request, we get the following successful result:

Ok, so all done. We can make a complete CORS request.


This article, I want to introduce what CORS is, what it means and the settings to make a simple CORS request in Laravel. Hopefully, these will give you a basic and applicable look into your problem. Thank you for following the article.




Share the news now

Source : Viblo