繁体   English   中英

具有强制参数的Laravel路径控制器

[英]Laravel Route Controller with Forced Parameter

所以我已经签出了PHP-LaravelLaravel中的 带参数路由 4强制性参数错误

但是使用所说的-我似乎无法使简单的路由成为可能,除非我不了解filter / get / parameters是如何工作的。

所以我想做的是路由/ display / 2的URL,其中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,并且会传递参数。 我想只将其限制为数字。

我也不想让它烦躁,因为索引在理想情况下是希望将此控制器与其他操作混合使用。

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

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

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

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

如何/何时有帮助?

假设您有多个需要参数的Route(让我们说id ):

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM