Question

Can I set a default route, so when I have a request like /home/index and /home, it would redirect to the home controller's index action, just like in other frameworks?
I know that I can set them one by one but I don't want to add a route for every request, I would like to use only one route for all requests.

No correct solution

OTHER TIPS

Theres two other types of controllers beside the basic controller. You can create these by specifying a special route to your controller. With this technique you don't have to create a route for every method just one per controller.

Resource Controller

This will create all the methods with the corresponding HTTP verb you need for managing one resource like a user or a product. There is a table in the documentation that contains which predefined route matches the predefined methods of the controller, that represents an action you can do with a method, like edit, create, destroy, etc:

Resource controller route-method list

Anyway, you still free to add extra methods and routes beside the resource controller methods and routes, just keep in mind that you have to do this before defining the resource controller route:

//Extra route for the resource controller.
Route::get('home/profile', 'HomeController@profile');
//Resource controller routes.
Route::resource('home', 'HomeController');

RESTful Controllers

I think this is what will fit better for your needs.
Creating a RESTful controller will automatically create a route for all methods that begins with a HTTP verb.

Route::controller('home', 'HomeController');

After this, you can create methods like these in your HomeController:

public function getIndex() {
    //Code.
}
public function postProfile() {
    //Code.
}

The framework will automatically create the routes for them, so you can access postProfile() through a HTTP POST to the /home/profile route. Also you can access getIndex() through a HTTP GET to the /home/index.

The documentation also mentions:

The index methods will respond to the root URI handled by the controller.

In our case that means that you can acces your getIndex() method through the /home/index and the /home routes too.
If you have a method that has multiple words in it (a word start with a camel case letter), then the generated route will have a - between the words, so the method getAdminProfile() will have a route called home/admin-profile.

Also as I told at the resource controller section, you can still create regular routes, just be sure to create them before you create the RESTful controller's route.

Final answer

Create a route: Route::controller('home', 'HomeController'); call your root method getIndex() and prefix every other method with a HTTP verb e.g. userTool() should become getUserTools().

If you're using Route::controller() just name your index() method getIndex().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top