How can I define a route differently if parameter

2019-06-15 21:33发布

问题:

I am using Laravel 5 and working on my local. I made a route with a parameter of {id} and another route with a specific name like so :

Route::get('contacts/{id}', 'ContactController@get_contact');
Route::get('contacts/new', 'ContactController@new_contact');

My problem here is that if I try to go at localhost/contacts/new it will automatically access to the get_contact method. I understand that I have made a {id} parameter but what if I want to call get_contact only if my parameter is an integer? If it is not, check if it's "new" and access to new_contact method. Then, if it's not an integer and not "new", error page 404.

How can I do that in Laravel 5?

Thanks for your help!

回答1:

Just add ->where('id', '[0-9]+') to route where you want to accept number-only parameter:

Route::get('contacts/{id}', 'ContactController@get_contact')->where('id', '[0-9]+');
Route::get('contacts/new', 'ContactController@new_contact');

Read more: http://laravel.com/docs/master/routing#route-parameters



回答2:

A simple solution would be to use an explicit approach.

Route::get('contacts/{id:[0-9]+}', 'ContactController@get_contact');
Route::get('contacts/new', 'ContactController@new_contact');


回答3:

Although the accepted answer is perfectly fine, usually a parameter is used more than once and thus you might want to use a DRY approach by defining a pattern in your boot function in the RouteServiceProvider.php file located under app/Providers (Laravel 5.3 and onwards):

 /**
 * Define your route model bindings, pattern filters, etc.
 *
 * @return void
 */
public function boot()
{
    Route::pattern('id', '[0-9]+');

    parent::boot();
}

This way, whereever you use your {id} parameter the constraints apply.



回答4:

There is also the possibility to just switch those around, because route file will go through all lines from top to bottom until it finds a valid route.

Route::get('contacts/new', 'ContactController@new_contact');
Route::get('contacts/{id}', 'ContactController@get_contact');

If you want to restrict that route to pure numbers, the marked solution is correct though.

Just adding it here, I know it is quite old ;)