Sling Academy
Home/PHP/Fixing Laravel Error: Access has been blocked by CORS policy (3 solutions)

Fixing Laravel Error: Access has been blocked by CORS policy (3 solutions)

Last updated: January 16, 2024

Understanding the CORS Policy Error in Laravel

CORS or ‘Cross-Origin Resource Sharing’ is a security feature implemented in web browsers to prevent the web applications from making requests to a domain different from the one which served the first web page. This error is frequently encountered during the API development with Laravel when an AJAX request is made from the client-side application running on a different domain than the server.

Solution 1: Update CORS Configuration

This solution focuses on updating the default CORS configuration in Laravel to allow requests from different origins. Laravel uses the package fruitcake/laravel-cors that is designed to handle CORS related issues.

Steps to implement:

  1. Install the CORS package if it’s not already included:
    composer require fruitcake/laravel-cors
  2. Publish the config file:
    php artisan vendor:publish --tag="cors"
  3. Edit the config/cors.php file to match the required origins, methods, and headers.
  4. Clear the configuration cache if necessary:
    php artisan config:clear

Example:

// Example configuration in config/cors.php
return [
    'paths' => ['api/*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['http://example.com'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['Content-Type', 'X-Requested-With'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => false,
];

This method is flexible and can be tailored to specific needs. It’s important, however, to not allow all origins in a production environment as it can expose your application to security risks.

Solution 2: Handling CORS in Middleware

Creating custom middleware in Laravel provides control over the CORS policy on a route-by-route basis.

Steps to implement:

  1. Create a new middleware:
    php artisan make:middleware CorsMiddleware
  2. Implement the CORS headers in the handle method.
  3. Register the middleware in app/Http/Kernel.php.
  4. Apply the middleware to the routes that require CORS handling.

Example:

// In app/Http/Middleware/CorsMiddleware.php
class CorsMiddleware {
    public function handle($request, Closure $next) {
        return $next($request)
          ->header('Access-Control-Allow-Origin', 'http://example.com')
          ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }
}

// In app/Http/Kernel.php
protected $routeMiddleware = [
    // ...
    'cors' => \App\Http\Middleware\CorsMiddleware::class,
];

// In routes/api.php or web.php
Route::middleware(['cors'])->group(function () {
    Route::get('/example', 'ExampleController@index');
});

This approach gives fine-grained control, but it requires more code setup and maintenance. It’s also essential to understand the security implications of manually setting these headers.

Solution 3: Fixing CORS issue on Front-end

Sometimes the issue can temporarily be bypassed on the front-end, especially during development.

Steps to implement:

  1. For local development, you might use proxies provided by development servers like the one used by create-react-app or Vue CLI.
  2. Configure the proxy to redirect requests to the Laravel application.

Example:

// In package.json (if using create-react-app)
"proxy": "http://localhost:8000",

This should not be used as a permanent solution as it only works in a development environment and does not address the CORS policy on the server. It bypasses the problem rather than fixing it.

Next Article: Laravel error – SQLSTATE[42S22]: Column not found: 1054 Unknown column (3 solutions)

Previous Article: Laravel Error 405: Method Not Allowed – How to Fix

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array