Turn Laravel CORS into dynamic CORS management

Hafiq Iqmal
2 min readApr 6, 2021

As stated, laravel-cors package allows you to send Cross-Origin Resource Sharing headers with Laravel middleware configuration.

Every time you alter origins, ports, etc.. in the cors.php, you need to push to git and if you have gitlab runner or any auto deployment script, it would be take sometimes to update in production.

The simplest answer is Cache.

Let’s create a new ServiceProvider named as CacheCorsServiceProvider

class CacheCorsServiceProvider extends CorsServiceProvider {}

If we take a look at CorsServiceProvider,

...
...
protected function corsOptions()
{
$config = $this->app['config']->get('cors');
}

the corsOptions get the cors setting from the config and pass it to CorsService. So, all we need is override this method and fetch the cors setting all the way from cache and set it into config array.

Why from cache? So that we can manage the cors setting in out CMS by altering the cache and without touching the cors.php file

class CacheCorsServiceProvider extends CorsServiceProvider 
{
protected function corsOptions()
{
$config = $this->getCorsData();

$this->app['config']->set('cors', $config);

return

--

--

Hafiq Iqmal
Hafiq Iqmal

Written by Hafiq Iqmal

Technical Lead | Software Engineer | Laravel Enthusiasts | Tech writer | UiTM Alumni | Husband | Proud father of a beautiful daughter