user1113314
user1113314

Reputation: 839

Laravel pattern routing to controller methods

How can I make a router like this

Route::any("/{controller}/{method}/{param}", "$controller@$method");

So that instead of specifing every single method in the routes file, I would be able to define a route for most cases for the convention http://example.com/controller/method/param

Upvotes: 2

Views: 1827

Answers (3)

jgarcias
jgarcias

Reputation: 699

@Emmanuel Figuerola Yes, it is worth to have the routing convention that most frameworks use out there, because if you need to define any special route, you can just define it without breaking anything and it is something very convenient for the developer, as he does not have to deal with hundreds of route definitions in the route files, which may be confusing, error prone and difficult to maintain.

Laravel becomes really cumbersome by defining a route for every view, for every method in a controller and for every AJAX callback when most of those routes can perfectly fit in the common and know pattern "controller/action/id", keeping simplicity, performance, maintainability and smaller code. I am still struggling to find a way to implement something similar in Laravel but it seems my efforts are in vain. The Route::controller(); was deprecated as of Laravel 4, if I remember well, in favor of the RESTful controllers.

Upvotes: 0

rmobis
rmobis

Reputation: 26992

You could use Route::controller, but you'd have to do it for every controller:

Route::controller('my-controller', 'MyController');

This will redirect my-controller/test to MyController@test or my-controller/double-test to MyController@doubleTest.

Upvotes: 2

Emmanuel Figuerola
Emmanuel Figuerola

Reputation: 1630

I don't really know why you would want to do this, I think you lose flexibility in the routes file with such approach. I'd rather have things explicitly defined, like so:

Route::get('/users/{id}', 'UserController@show');
Route::post('/users', 'UserController@store');

And, as you can see, different routes, despite being handled by methods belonging to the same controller, might have different amounts and kind of parameters (e.g.: getting a specific user requires sending an ID parameter, but storing a new user doesn't require sending parameters, at least not via the URL).

Besides,

Route::any("/{controller}/{method}{param}" ...

means everything inside {} is a parameter, including {param}.

Seems you want a generic one-liner route. Is it really worth it?

Upvotes: 2

Related Questions