You can't share resources between two servers or domains, right? So, if you're stumped by this riddle, we've got a solution for you.

In this article, I'll show you how to enable and interact with CORS (Cross-Origin Resource Sharing) in Laravel. CORS can be installed and configured to fix the missing CORS header 'access-control-allow-origin' issue.

Generally, this problem happens when a request is made from a different server or origin due to a lack of security consensus between two servers. We normally get a warning that says "No 'Access-Control-Allow-Origin' header is present on the requested page." CORS is a protocol that allows two domains to communicate with each other.

CORS (cross-origin resource sharing) is a method that permits restricted web page resources to be requested from a domain other than the one that supplied the first resource.

Table of Content

  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

1. laravel CORS Example

How can you make your REST API backend CORS compliant? We must first install a new Laravel application.

composer create-project laravel/laravel laravel-cors-tutorial --prefer-dist

Add the following to the project folder:

cd laravel-cors-tutorial

If you already have the app installed, skip this step and run the command to begin testing CORS in the Laravel app.

php artisan serve

2. CORS Middleware Nitty-Gritty

The config/cors.php file is generated along with the new app installation. Laravel supports the following cors setups.

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

<?php
return [
    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */
    'paths' => ['api/*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => false,
];

3. Create API in Laravel

We need one to enable CORS in API, thus go to routes/api.php and paste in the code below.

<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::get('/demo-url',  function  (Request $request)  {
   return response()->json(['Laravel CORS Demo']);
});

4. Make Http GET Request with AJAX

AJAX will be used to send the Http GET request. Create a new HTML template and call it demo.html. To receive the response, use the jQuery CDN link, define the AJAX method, and pass the Laravel API.

<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
        integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <title>Laravel CORS Middleware Demo</title>
</head>
<body>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
    <script>
        $.ajax({
            type: "GET",
            dataType: "json",
            url: 'http://localhost:8000/demo-url',
            success: function (data) {
                console.log(data);
            }
        });
    </script>

</body>
</html>

5. Malevolent Laravel CORS Error

Because we have two separate domains attempting to exchange data, a CORS related error (No 'Access-Control-Allow-Origin' header is present on the requested resource.) happened. And, yeah, we haven't even turned on CORS.

Access to XMLHttpRequest at 'http://localhost:8000/demo-url' from origin 'null'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is
present on the requested resource.

6. Installing CORS Package in Laravel

Now that we know what the problem is, we can focus on treating it. Simply install the fruitcake/laravel-cors package using Composer.

composer require fruitcake/laravel-cors

7. Registering CORS Middleware

In your Laravel application, we've included the crucial CORS (Cross-Origin Resource Sharing) headers support. Now we must set it up in our application.

Finally, in the app/Http/Kernel.php file, add the FruitcakeCorsHandleCors class at the top of the $middleware array to enable CORS for all our routes.

protected $middleware = [
  \Fruitcake\Cors\HandleCors::class,
    // ...
    // ...
];

To deal with resource sharing on several domains, we implemented CORS in Laravel.

I hope you will like the content and it will help you to learn laravel CORS Example: How to Enable CORS in Laravel?
If you like this content, do share.


Recommended Posts

View All

Recommended Posts

View All

Laravel 9 GEO Chart Example using LavaCharts


Learn how to create interactive GEO charts with Laravel 9 and LavaCharts. Visualize your data on maps and improve data analysis. Check it out now!

whereIn and whereNotIn Query Example in Laravel


In this model, we will see the Laravel whereIn and whereNotIn query model. Laravel whereIn and whereNotIn query example, laravel whereIn, laravel wher...

Effortlessly Handle File Uploads in Laravel with FilePond


We'll walk through the process of setting up FilePond, creating a file upload form, and handling file uploads in Laravel

Laravel where clause with date_format() example


laravel db raw where, laravel where date_format, laravel date_format mysql where, laravel date_format example, laravel where with month

Laravel 9 Database Seeder Tutorial Example


Let's go over all of the procedures that will help us understand how the database seeder works in the Laravel application to generate dummy data.