Reputation: 15673
I have the following routes in my Laravel 3 RESTful api project
Route::delete('/(:any)', 'resources@destroy');
Route::delete('users/(:any)', 'users@destroy');
The problem I am having is when a user sends a delete request to /users/
What I want to happen is that the users@destroy
route is called with parameter null
. In my controller I have an exception for a user trying to delete a null
resource.
What seems to be happening is that the resource@destroy
route is called with parameter users
. This obviously has the undesired affect of deleting the users resource.
I know I could modify my .htaccess but technically /users/ does belong to the users controller not the resources controller. I want to maintain that relationship.
I was wondering if there is a simple way to solve this from within Laravel?
EDIT: have the above working with the answer below. Now I have an error in my get routes
Route::get('users/(:any?)', 'users@show');
Route::get('users', 'users@index');
/users and /users/ both call users@index which I don't want.
I need GET /users to go to users@index and GET /users/ to go to users@show with null parameter
Upvotes: 0
Views: 2669
Reputation: 15673
I worked around the trailing slash by adding a filter to my routes
Route::group(array('before' => 'trailingslash'), function()
{
//routes in here
});
Route::filter('trailingslash', function() {
$current = URI::full();
if(substr($current, -1) == '/'){
return return Response::error('404');
}
});
Upvotes: 1
Reputation: 6393
one point you need to consider.
Routes are defined without a front-slash. The only exception to this is the default route which is represented with only a front-slash.
so Route::delete('/(:any)', 'resources@destroy')
will cause undesired result.
Moreover, your order is wrong.
(:any)
will match user
too and will send the request to resources
controller.
so what you need to do is,
resources
considering according to the rules. like resources/delete
etc.....What I want to happen is that the users@destroy route is called with parameter null. In my controller I have an exception for a user trying to delete a null resource.
to do this, (after making the changes above....)
change the route of user/(:any)
to user/(:any?)
which will make the 2nd segment optional.
After that, straight forward.
$foo = URI::segment(2, null);
//Rest will follow.
Now, the following code,
Route::get('users/(:any?)', 'users@show');
Route::get('users', 'users@index');
does not make any sense.
if i type user
, what the router is suppose to take?
user@show
with no optional segment or user@index
?
Routes are design so that it removes the ambiguity. You are going in the opposite direction with making it all ambiguity.
just make a simple route.
like show
user/show
delete
user/delete
edit
user/edit
etc....
The type of routing you are applying is confusing for both users and developers as it carries ambiguity.
Upvotes: 0