Eric Evans
Eric Evans

Reputation: 672

Laravel 4 Resource Routing

I would like to know how to put constrains on resource routes $id. For example I would like to get

user/{id}

to make sure that id in just a number and nothing else. I've registered my resources with

Route::resource('user','UserController');

Upvotes: 1

Views: 519

Answers (2)

codeatbusiness
codeatbusiness

Reputation: 41

Sorry for the delay. I just saw your question.

If you use Laravel 4.1 you can use the Route::resource method as follow:

Route::resource('user', 'UserController', array('only' => array('create', 'store', 'update', 'destroy')));

Then you can then add another action using the Route::get() method as follow:

Route::get('customaction/{id}', 'UserController@customAction')

You can set the the required parameters to this custom route.

Upvotes: 0

Alexandre Butynski
Alexandre Butynski

Reputation: 6746

You could use route parameters as explain in the documentation. The (quite verbose) solution will be :

Route::get('user',           array('uses' => 'UserController@index'));
Route::get('user/create',    array('uses' => 'UserController@create'));
Route::post('user',          array('uses' => 'UserController@store'));
Route::get('user/{id}',      array('uses' => 'UserController@show'))->where('id', '[0-9]+');
Route::get('user/{id}/edit', array('uses' => 'UserController@edit'))->where('id', '[0-9]+');
Route::put('user/{id}',      array('uses' => 'UserController@update'))->where('id', '[0-9]+');
Route::delete('user/{id}',   array('uses' => 'UserController@destroy'))->where('id', '[0-9]+');

Unfortunately, this will thrown a 500 (NotFoundHttpException) and not a 404, but it could protect you against security or database inconsistency issues.

Upvotes: 4

Related Questions