2

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

3 Answers 3

2

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?

Sign up to request clarification or add additional context in comments.

Comments

2

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.

3 Comments

I had not read about Route::controller. Looks cool, thanks for the info.
This doesn't work. It says Controller method not found.
@akifquddus Please note this answer was given regarding Laravel 4. Things may have changed on Laravel 5.
0

@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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.