【问题标题】:Laravel Route Controller with Forced Parameter带有强制参数的 Laravel 路由控制器
【发布时间】:2013-07-14 01:59:18
【问题描述】:

所以我已经签出 PHP - Routing with Parameters in LaravelLaravel 4 mandatory parameters error

但是使用所说的-除非我不了解过滤器/获取/参数的工作原理,否则我似乎无法实现简单的路由。

所以我想做的是有一个路由 URL 为 /display/2 其中 display 是一个动作,而 2 是一个 id,但我想将其限制为仅数字。

我以为

Route::get('displayproduct/(:num)','SiteController@display');
Route::get('/', 'SiteController@index');

class SiteController extends BaseController {

public function index()
{

    return "i'm with index";
}

public function display($id)
{
    return $id;
}
}

问题是它会抛出 404 如果我使用

Route::get('displayproduct/{id}','SiteController@display');

它会传递参数,但是 URL 可以是 display/ABC 并且它会传递参数。 我想将其限制为仅数字。

我也不希望它是安静的,因为 index 理想情况下我希望将此控制器与不同的操作混合。

【问题讨论】:

    标签: php laravel laravel-4 pattern-matching


    【解决方案1】:

    您还可以定义全局路由模式

    Route::pattern('id', '\d+');
    

    这如何/何时有用?

    假设您有多个需要参数的路由(比如说id):

    Route::get('displayproduct/{id}','SiteController@display');
    Route::get('editproduct/{id}','SiteController@edit');
    

    您知道,在所有情况下,id 都必须是一个数字。

    然后可以使用Route patterns 对所有路由的所有id 参数设置一个约束

    Route::pattern('id', '\d+');
    

    执行上述操作将确保所有接受id 作为参数的路由都将应用id 必须是数字的约束。

    【讨论】:

    • 对不起 - 我不明白那个 - 我还没有看到有人使用那个
    • 很抱歉迟到了你的答案 - 如果模式是实际模式,它是有效的。如果它的数字是首选,因为您可以将其限制为数字。与 is_numeric 相比,它大约相当于进行 preg_reg 匹配 - is_numeric 产生更快的结果
    • @azngunit81 如果你想重用一个模式,我认为这是一个更好的选择——与我们使用函数的原因相同。此外,您要匹配的模式也无关紧要,这也是使用正则表达式。
    【解决方案2】:

    假设你使用的是 Laravel 4 你不能使用 (:num),你需要使用正则表达式来过滤。

    Route::get('displayproduct/{id}','SiteController@display')->where('id', '[0-9]+');
    

    【讨论】:

    • 正确,所有约束都使用正则表达式完成,使用 {id} 将允许任何匹配。看看laravel.com/docs/routing#route-parameters
    • Code Happy 适用于 Laravel 3,请查看 Code Bright(适用于 Laravel 4)codebright.daylerees.com
    • 哇...如果我遇到了这个 - 该网站需要在前 10 名搜索结果中,以避免头痛。 -tks 链接
    • @dragoon 如果我想为 id 提供选择,比如只能传递值 1,3 和 5,该怎么办?我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    • 2014-12-10
    • 2018-04-16
    相关资源
    最近更新 更多