I'm building a CMS and trying to use a better approach when it comes to the routes. Let's say I have a "pages" controller and the following methods: "create", "edit" and "delete". The URIs for them would be like this:
admin/pages/create
admin/pages/edit
admin/pages/delete
I could hardcode the routes and everything would be fine, but It will be a mess in no time. I've searched a lot and found the code below:
Route::any('admin/(.*)', array('defaults' => 'index', 'uses' => 'admin.METHOD@(:1)'));
The idea is to detect the method from the URL and replace it in the "admin.METHOD@". The code would handle the request and direct it to the correct controller method and I can't figure out how to do it.
Any help would be perfect.
Okay you can do this in Laravel 3 but there are a few gotchas that you need to be aware of. First this is how it might look.
Route::any('admin/(:any)/(:any)', 'admin.(:1)@(:2)');
That would match a URI of yourapp.dev/admin/pages/create
and route it to the get_create
method on the Admin_Pages_Controller
controller.
The first thing you need to be aware of here is when there are hyphens in your URI. You could end up with Admin_User-accounts_Controller
because Laravel doesn't do any of that detection. In these cases it might be easier to use Controller::call()
in the route.
Route::any('admin/(:any)/(:any)', function($controller, $method)
{
return Controller::call("{$controller}@{$method}");
});
At the moment that is the same as the earlier example. You'd need to do any replacement and studly casing to the variables. You could also take that example by making the method optional and reverting to a default method such as index
.
Basically what you're trying to achieve is resourceful routing, which is handled a lot cleaner in Laravel 4. I did a quick search of the Laravel 3 bundle repository and came up with Routely. From the looks of this bundle it does a lot of the heavy lifting for you and is quite customizable.