Can't use "url" helper function in config files in Laravel

Nikunj Kanetiya 2018-11-28

Objective

Using url helper in config files breaks Artisan, so what's the way to use url() in config for Socialite and others

You might face this issue first time when you use Socialite in Laravel. To using socailite you need to set services.php like these

'facebook' => [
    'client_id' => 'fb-client-id',
    'client_secret' => 'fb-client-secret',
    'redirect' => url('auth/redirect/facebook'),
],

'google' => [
    'client_id' => 'google-client-id',
    'client_secret' => 'google-client-secret',
    'redirect' => url('auth/redirect/google'),
],

Although the HTTP application continues to work normally, I’ve noticed that any subsequent Artisan commands fail with the following RuntimeException.

Error Output: PHP Catchable fatal error: Argument 2 passed to Illuminate\Routing\UrlGenerator::__construct() must be an instance of Illuminate\Http\Request, null given, called in /home/vagrant/Sites/southsidewrestling.co.uk/vendor/laravel/framework/src/Illuminate/Routing/RoutingServiceProvider.php on line 56 and defined in /home/vagrant/Sites/southsidewrestling.co.uk/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php on line 81

This also occurs if you try to resolve the helper in its “longhand” form:

return [
    'facebook' => [
        'redirect' => app('url')->to('auth/redirect/facebook'),
    ],
];

It happens because all configurations are loaded way too early in framework lifecycle. So at that time you can't use function `url()`

So what's the way!! There are many.. Here is what I preferred by creating new Service Provider to load URLs for configs. 

Create new service provider called 'ConfigServiceProvider'. If you are not aware, create a new file 'ConfigServiceProvider.php' in 'app/Providers' directory contains following code

        makeAbsoluteUrls();
    }

    /**
     * Make relative urls into absolute urls.
     *
     * @return void
     */
    public function makeAbsoluteUrls()
    {
        foreach (Config::get('services') as $key => $config) {
            if (! isset($config['redirect'])) {
                continue;
            }

            Config::set("services.$key.redirect", url($config['redirect']));
        }
    }
}
 

Summary

You can add other stuff as well. It is pretty simple and organized way to setup configs with using frameworks functions.

Created on : 2018-10-04
Written by

Nikunj Kanetiya

Full Stack Web Developer

Tags
Web Development
Laravel
Url Helper