Laravel & CORS

Hello, fellow Laravel developers! In this post, I’m going to show you how to enable CORS (Cross-Origin Resource Sharing) in your Laravel application. CORS is a security feature that allows you to control which websites can access your APIs or other resources from different origins (domains). This is useful when you want to expose your APIs to third-party websites or when your website spans multiple domains or subdomains.

There are different ways to configure CORS in Laravel, but I’m going to focus on using the laravel-cors package by Barry vd. Heuvel. This package allows you to send CORS headers with Laravel middleware configuration. It’s very easy to install and use, so let’s get started!

First, you need to install the package using Composer:

ShellScript
composer require barryvdh/laravel-cors

Next, you need to register the middleware in your app/Http/Kernel.php file. You can either add it as a global middleware that runs on every request, or as a route middleware that runs on specific routes or groups. For example:

PHP
// Global middleware
protected $middleware = [
  // ...
  \Barryvdh\Cors\HandleCors::class,
];

// Route middleware
protected $routeMiddleware = [
  // ...
  'cors' => \Barryvdh\Cors\HandleCors::class,
];

Then, you need to publish the configuration file using this command:

ShellScript
php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

This will create a config/cors.php file where you can fine-tune your CORS settings. Here are some of the options you can configure:

  • paths: The paths where CORS should be enabled.
  • allowed_origins: The origins that are allowed to access your resources. You can use * for all origins or specify an array of domains.
  • allowed_methods: The HTTP methods that are allowed for cross-origin requests. You can use * for all methods or specify an array of methods.
  • allowed_headers: The HTTP headers that are allowed for cross-origin requests. You can use * for all headers or specify an array of headers.
  • exposed_headers: The HTTP headers that are exposed to the browser. By default, no headers are exposed.
  • max_age: The maximum age (in seconds) of preflight responses that can be cached by the browser.
  • supports_credentials: Whether cookies and other credentials are supported for cross-origin requests.

For more details on these options and their default values, check out the documentation of the package.

That’s it! You have successfully enabled CORS in your Laravel application. Now you can test it by making cross-origin requests from different websites and see if they work as expected.

I hope you found this post helpful and learned something new about Laravel and CORS. If you have any questions or feedback, feel free to leave a comment below. Happy coding!

Scroll to Top