Turn Laravel CORS into dynamic CORS management

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 parent::corsOptions();
}
private function getCache($app)
{
return $app->make('cache')->tags('system-cors');
}

private function getCorsData()
{
return $this->getCache($this->app)->rememberForever('cors', fn() => $this->app['config']->get('cors'));
}
}

Then, register is provider in app.php

providers => [
...
App\Providers\CacheCorsServiceProvider::class,
]

If somehow you want to store and fetch from database, here just the example,

private function getCorsData()
{
if (!$cors = Model::getCors()) {
return Model::createCors($this->app['config']->get('cors'));
}

return $cors;
}

Now all set! You can start managing your cors dynamically without touching the original cors file. If you altering the cors file, you need to clear the cache first. Else, the config wont reflect unless you have some logic there to check if there is a changes in the file.

BTW, I wont show how to create the UI because its just the data from cors array where you can design by your own.

That’s all. Thanks for your time

~~~ Happy Working~~~

Software Engineer at Teratotech.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store