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/[email protected]/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 Send SMS Notification to Mobile Phone Tutorial


Learn how to use the Vonage (nexmo) package in a Laravel application to send an SMS notice to a mobile phone.

Laravel 9 FullCalendar Ajax Tutorial with Example


We&amp;#039;ll show you how to use the Fullcalendar JavaScript event calendar plugin to add FullCalendar to your Laravel app and create and cancel eve...

Laravel 8 Import Export Excel & CSV File Example


Using the Maatwebsite/Laravel-Excel package, you will learn how to easily import and export Excel and CSV files in the Laravel 8 application while com...

Google Map with Multiple Marker and Info Box in Laravel


This tutorial will teach you how to use Laravel to integrate a Google Map with numerous markers and an info box.

How to Implement Gravatar Image using thomaswelton/laravel-gravatar in Laravel 9


Learn how to easily implement Gravatar image using thomaswelton/laravel-gravatar in Laravel 9. Enhance user profiles with personalized images.