带有强制参数的 Laravel 路由控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17667206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:08:44  来源:igfitidea点击:

Laravel Route Controller with Forced Parameter

phplaravellaravel-4pattern-matching

提问by azngunit81

So i have checked out PHP - Routing with Parameters in Laraveland Laravel 4 mandatory parameters error

所以我检查了 PHP - Routing with Parameters in LaravelLaravel 4 强制参数错误

However using what is said - I cannot seem to make a simple routing possible unless im not understanding how filter/get/parameters works.

然而,使用所说的 - 我似乎无法使简单的路由成为可能,除非我不了解过滤器/获取/参数的工作原理。

So what I would like to do is have a route a URL of /display/2 where display is an action and the 2 is an id but I would like to restrict it to numbers only.

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

I thought

我想

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;
}
}

The problem is that it throws a 404 if i use

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

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

it will pass the parameter however the URL can be display/ABC and it will pass the parameter. I would like to restrict it to numbers only.

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

I also don't want it to be restful because index I would ideally would like to mix this controller with different actions.

我也不希望它是宁静的,因为我希望将这个控制器与不同的动作混合在一起。

回答by dragoon

Assuming you're using Laravel 4 you can't use (:num), you need to use a regular expression to filter.

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

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

回答by Lucky Soni

You may also define global route patterns

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

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

How/When this is helpful?

这如何/何时有帮助?

Suppose you have multiple Routes that require a parameter (lets say id):

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

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

And you know that in all cases an idhas to be a digit(s).

而且您知道在所有情况下 anid都必须是数字。

Then simply setting a constrain on ALL idparameter across all routes is possible using Route patterns

然后id可以使用简单地在所有路由上设置对所有参数的约束Route patterns

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

Doing the above will make sure that all Routes that accept idas a parameter will apply the constrain that idneeds to be a digit(s).

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