How can I define a route differently if parameter is not integer

后端 未结 4 1346
无人及你
无人及你 2021-01-17 08:08

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/         


        
相关标签:
4条回答
  • 2021-01-17 08:57

    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

    0 讨论(0)
  • 2021-01-17 09:04

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

    0 讨论(0)
  • 2021-01-17 09:07

    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.

    0 讨论(0)
  • 2021-01-17 09:14

    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');
    
    0 讨论(0)
提交回复
热议问题