How to Enable CORS in Laravel

In this tutorial you will learn about the How to Enable CORS in Laravel and its application with practical example.

In this How to Enable CORS in Laravel tutorial, I will show you how to enable CORS (Cross-Origin Resource Sharing) in Laravel 8 application. In this tutorial you will learn to enable CORS in laravel application. You will also learn to install and configure CORS to get rid of CORS header ‘access-control-allow-origin’ missing problem. When a request is made between two between two different servers or domains because of security concern we usually get No ‘Access-Control-Allow-Origin’ warning. Enabling CORS authenticate the resource sharing between two different domains.

How to Enable CORS in Laravel

In this step by step tutorial I will demonstrate you how to enable CORS (Cross-Origin Resource Sharing) in Laravel 8. Please follow the instruction given below:

  1. Laravel CORS Example
  2. CORS Middleware Nitty-Gritty
  3. Create API in Laravel
  4. Make Http GET Request with AJAX
  5. Malevolent Laravel CORS Error
  6. Installing CORS Package in Laravel
  7. Registering CORS Middleware

Laravel 8 CORS Example

First of all we need to create a fresh laravel project, download and install Laravel 8 using the below command

switch into the project directory using following command:

Run the command to start the laravel app.

CORS Middleware Nitty-Gritty

After installing laravel application there would be a config/cors.php file generated. Below is list of cors related configurations available in file.

  • CORS configuration paths
  • Allowed methods
  • Allowed origins patterns
  • Allowed headers
  • Exposed headers
  • Max age
  • Supports credentials

config/cors.php

Create API in Laravel

Go to routes/api.php and put the following code to enable CORS in API.

Make Http GET Request with AJAX

In this step we will create a demo.html file and make Http GET request using AJAX to laravel api.

Making ajax request we will get CORS related error (No ‘Access-Control-Allow-Origin’ header is present on the requested resource.) because we have two different domain trying to exchange data.

Installing CORS Package in Laravel

In this step, we will install fruitcake/laravel-cors Package via the composer dependency manager. Use the following command to install fruitcake/laravel-cors Package.

Registering CORS Middleware

Now we have to include \Fruitcake\Cors\HandleCors class at the top inside $middleware array to enable CORS for all our routes in app/Http/Kernel.php file.

This way we have enabled CORS in our laravel application.

In this tutorial we have learn about the How to Enable CORS in Laravel and its application with practical example. I hope you will like this tutorial.