So i have checked out PHP - Routing with Parameters in Laravel and Laravel 4 mandatory parameters error
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.
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
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.
I also don't want it to be restful because index I would ideally would like to mix this controller with different actions.
假设您使用的是Laravel 4,则无法使用(:num),则需要使用正则表达式进行过滤。
Route::get('displayproduct/{id}','SiteController@display')->where('id', '[0-9]+');
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
):
Route::get('displayproduct/{id}','SiteController@display');
Route::get('editproduct/{id}','SiteController@edit');
And you know that in all cases an id
has to be a digit(s).
Then simply setting a constrain on ALL id
parameter across all routes is possible using Route patterns
Route::pattern('id', '\d+');
Doing the above will make sure that all Routes that accept id
as a parameter will apply the constrain that id
needs to be a digit(s).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.