【问题标题】:Laravel route with id and name带有 id 和名称的 Laravel 路由
【发布时间】:2015-07-07 06:23:11
【问题描述】:

我生成这样的 URL:

URL::action('FieldsController@show',['id' => $field->id, 'head' => cleanUrl($field->head)])

在我的路线中,我有:

Route::get('/field/{head}-{id}', 'FieldsController@show');

而且它不起作用,只有当我像这样将 ID 放在首位和 HEAD 放在第二位时:

Route::get('/field/{id}-{head}', 'FieldsController@show');

有人有想法吗?我需要在 URL 中的 HEAD 之后有 ID

【问题讨论】:

    标签: laravel laravel-4 routes


    【解决方案1】:

    你不能像这样做路由

    {head}-{id}
    

    你需要这样做:

    Route::get('/field/{head}/{id}', 'FieldsController@show');
    

    然后在您的show() 函数中您可以自己组合它们:

    function show($head, $id)
    {
         $var = $head.'-'.$id;
         // do whatever you want with $var here
    }
    

    【讨论】:

    • 在您的控制器中。你的路线被称为FieldsController@show - 所以它说它正在使用show() 函数?
    • 哦,我的错误..现在我明白了。谢谢你。
    • @TheShiftExchange 为什么不能这样完成路由?
    • @Ravan - 您不能在 url 中通过-安全地拆分变量。当 Laravel 尝试解析路由并确定哪个文本属于哪个变量时,尝试这种方式会出现问题。使用/ 是唯一安全 的方法,以确保在解析时正确的文本最终出现在正确的变量中。例如 - 如果有人键入 /field/this-is-an-example - 哪些变量去哪里? Laravel 无法确定使用原始设计。但这有效:/field/this-is/an-example
    【解决方案2】:

    我正在这样使用它,它工作得很好:

    Route::get('/blog/{slug}-{article}', [App\Http\Controllers\BlogController::class, 'article'])->name('blog.article')->where(['slug' => '[\w]+[^\d]+', 'article' => '[\d]+$']);
    

    【讨论】:

      猜你喜欢
      • 2015-04-04
      • 1970-01-01
      • 2019-03-07
      • 2018-11-30
      • 1970-01-01
      • 2020-08-06
      • 2019-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多