【问题标题】:How to use route helper in config file如何在配置文件中使用路由助手
【发布时间】:2020-10-21 04:56:39
【问题描述】:

所以我有一个名为 services.php 的配置文件,其内容类似于

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

但我想要这样:

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

但是tinker 使用类似代码会报告:

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

但如果我使用第一个赞,然后打开tinker 并粘贴:

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

效果很好

【问题讨论】:

    标签: php laravel routes helper


    【解决方案1】:

    我解释了如何加载配置 here

    您收到此错误的原因“可能”是在加载配置后加载/引导辅助方法。

    一种方法是使用RouteServiceProvider 为您需要的这些类型用法初始化/设置配置。

    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'])));
        }
    }
    

    编辑:

    github 中也有 5 年以上的问题,提到了与您类似的案例。

    【讨论】:

    • 是否允许这样做或被视为“更改框架文件”,因此不建议这样做?
    • 我不认为这是“更改框架”文件,您可以创建自己的 ServiceProvider 或添加现有的 ServiceProvider,例如 Application、Route 或 EventServiceProvider。这是完全“允许的”。 @Berto99
    猜你喜欢
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 2018-07-18
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多