Search code examples
phplaravelrouteshelper

How to use route helper in config file


So i have a config file called services.php with content like

[
    'facebook' => [ 'url' => 'https://...']
]

But i want to have it like this:

[
    'facebook' => [ 'url' => url(route('socialite-callback', ['provider' => 'facebook']))]
]

However tinker with this like of code will report:

Argument 2 passed to Illuminate\Routing\UrlGenerator::__construct() must be an instance of Illuminate\Http\Request, null given, called in /laravel/justitalianwine_ecommerce/vendor/laravel/framework/src/Illuminate/Routing/RoutingServiceProvider.php on line 68

But if i use the first like, and then open tinker and paste this:

url(route('socialite-callback', ['provider' => 'facebook']))

it works fine


Solution

  • I explained how the configs are loaded here.

    The reason you are getting this error is "probably" that helper methods are loaded/bootstrapped after the configuration is loaded.

    One way to do it would be using RouteServiceProvider to initialize/set the config for these type usages that you need.

    class RouteServiceProvider extends ServiceProvider
    {
        // other methods and fields...
    
        public function map()
        {
            $this->mapApiRoutes();
            $this->mapWebRoutes();
            $this->mapServiceRoutes();
        }
    
        protected function mapServiceRoutes()
        {
            config()->set('services.facebook.url', url(route('socialite-callback', ['provider' => 'facebook'])));
        }
    }
    

    Edit:

    Also there is 5+ years old issue in github mentioning a similar case to yours.