Rails-like HTML-friendly resourceful routing in Laravel
Friday, June 7, 2013 at 5:37PM While Laravel 4's routing engine is certainly powerful, it didn't quite fulfil my desires with resourceful, RESTful routing. By default Laravel's resource routing is geared toward writing APIs - making use of the full range of HTTP verbs - and this isn't very helpful when working with a web browser.
Rather than replicate Rails' resource routing, where the HTTP verb is faked with a _method parameter, I decided to write a small helper function to manually route the basic set of resource routes to a controller.
The function looks like this:
// Rails-like routes
function htmlResource($resources, $controller)
{
$resource = str_singular($resources);
Route::get($resources,
array( 'as' => $resources, 'uses' => $controller . '@getIndex' ));
Route::get($resources . '/{id}',
array( 'as' => $resource, 'uses' => $controller . '@getShow' ));
Route::get($resources . '/{id}/new',
array( 'as' => 'new_' . $resource, 'uses' => $controller . '@getNew' ));
Route::post($resources,
array( 'as' => 'create_' . $resource, 'uses' => $controller . '@postCreate'));
Route::get($resources . '/{id}/edit',
array( 'as' => 'edit_' . $resource, 'uses' => $controller . '@getEdit' ));
Route::post($resources . '/{id}',
array( 'as' => 'update_' . $resource, 'uses' => $controller . '@postUpdate' ));
Route::post($resources . '/{id}/delete',
array( 'as' => 'delete_' . $resource, 'uses' => $controller . '@postDelete' ));
}
...and should be called in your routes file, where the first parameter is the name of the resource and the second parameter the controller. This will route the CRUD actions and name each route too.
One call to this function:
htmlResource('users', 'UserController');
Gives me a php artisan routes output of this:
+-------------------------+-------------+---------------------------------+
| URI | Name | Action |
+-------------------------+-------------+---------------------------------+
| GET /users | users | UsersController@getIndex |
| GET /users/{id} | user | UsersController@getShow |
| GET /users/{id}/new | new_user | UsersController@getNew |
| POST /users | create_user | UsersController@postCreate |
| GET /users/{id}/edit | edit_user | UsersController@getEdit |
| POST /users/{id} | update_user | UsersController@postUpdate |
| POST /users/{id}/delete | delete_user | UsersController@postDelete |
+-------------------------+-------------+---------------------------------+



