【问题标题】:Laravel route variables with multiple "-"带有多个“-”的 Laravel 路由变量
【发布时间】:2020-04-19 09:09:40
【问题描述】:

所以我的 laravel 应用程序中有一个类别路由,如下所示:

Route::get('all-{category}-listings', 'CategoryController@index')->name('category');

当我转到以下 URL localhost:8000/all-test-listings 时,它工作正常, 但是当一个类别的名称中也有连字符时,它会给我一个 404,例如 localhost:8000/all-test-test-listings

有人知道解决这个问题的方法吗?

【问题讨论】:

    标签: laravel


    【解决方案1】:

    您可以在路线上使用“正则表达式约束”来启用带有破折号的类别:

    Route::get('all-{category}-listings', 'CategoryController@index')
    ->where('category', '[A-Za-z0-9-]+')
    ->name('category');
    

    https://laravel.com/docs/7.x/routing#parameters-regular-expression-constraints

    【讨论】:

    • 如果有人想知道为什么这仍然不起作用,请在每次更改为 web.php 后输入 php artisan route:cache
    【解决方案2】:

    如果您希望路由参数始终受 给定正则表达式,您可以使用模式方法。你应该 在你的 boot 方法中定义这些模式 RouteServiceProvider:

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        Route::pattern('category', '[a-z0-9-]+');
    
        parent::boot();
    }
    

    一旦定义了模式,它就会自动应用于所有 使用该参数名称的路由:

    Route::get('all-{category}-listings', function ($category) {
        // {category} has to be alpha numeric (lowercase), but can include a dash
    });
    

    【讨论】:

      猜你喜欢
      • 2015-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 2013-11-07
      • 2016-04-21
      • 2016-01-20
      相关资源
      最近更新 更多