【问题标题】:How to use ->where() condition on Route Params in Laravel如何在 Laravel 的 Route Params 上使用 ->where() 条件
【发布时间】:2018-10-24 11:58:59
【问题描述】:

我将Laravel 5.7中Route的默认参数改成

Route::resource('questions', 'QuestionController')->parameters(['questions' => 'question_slug']);

但是我很困惑如何将正则表达式模式设置为那个新参数,我想在这个参数上应用slug_regex,我试过这个:

Route::resource('questions', 'QuestionController')->parameters(['questions' => 'question_slug'])->where(['slug' => '^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$']);

但是得到这个错误:

BadMethodCallException 方法 Illuminate\Routing\PendingResourceRegistration::where 不存在。

【问题讨论】:

    标签: laravel parameters routes


    【解决方案1】:

    最后我在一行代码中找到了解决方案,要在参数/参数上设置正则表达式验证,只需导航到YourProjectName\app\Providers\RouteServiceProvider.php,您将在其中找到名为boot的方法,它包含此代码默认情况下;

    public function boot()
    {
        //
    
        parent::boot();
    }
    

    只需在此处添加您的参数即可;

    Route::pattern('parameter', 'regex-rule-here');

    所以你的代码将是;

    public function boot()
    {
        //
    
        Route::pattern('slug', '[\w\d\-\_]+');
    
        parent::boot();
    }
    

    对于更多参数,只需将您的参数传递到数组中:

    Route::pattern(['1st-para' => 'regex-rule-here', '2nd-para' => 'regex-rule-here']);

    【讨论】:

      【解决方案2】:

      所以Route 在 Laravel 中并不是一个真正的类,实际上是一个 Facade,它可以让你像静态一样访问真正的类。

      当查看resource() 函数时,这使您可以访问的真正类是Illuminate\Routing\Router(这是在您编写Route::resource() 时调用的),我们可以看到它返回一个Illuminate\Routing\PendingResourceRegistration 对象和where() 方法不适用于此类。

      那么如何解决您的问题呢?有两种方法,您可以检查slug 在您的controller 操作中是否有效,或者您可以创建一个middleware,因为资源路由可以附加middleware

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-15
        • 1970-01-01
        • 2022-11-12
        • 2022-10-23
        • 2021-07-12
        • 2015-10-26
        • 1970-01-01
        • 2021-08-24
        相关资源
        最近更新 更多