'How to define two different routes to the same controller?

Is there way to define the following in a cleaner way?

Route::get('/', 'SiteController@home')->name('home');
Route::get('/home', 'SiteController@home');

What would be the recommended, most performant Laravel way?



Solution 1:[1]

You can use regex to map multiple routes to one controller. Not sure if it looks cleaner, or even 'better'.

$router->get('/{home?}', 'SiteController@home')
       ->where('home', '(home|another_home_route)')
       ->name('home');

This will work for the routes:

  • /
  • /home
  • /another_home_route

Solution 2:[2]

Route::get('/{verb?}', 'SiteController@home');

And then handle the logic inside the controller function

function home($verb = 'empty') {
    if ($verb == 'home') {
         // do home thing
    } else if ($verb == 'empty') {
        // do empty thing
    }
}

https://laravel.com/docs/5.4/routing section Optional Parameters

Solution 3:[3]

In laravel 8 you can do that:

Route::controller(HomeController::class)->group(function () {
    Route::get('/home', 'index');
    Route::get('/', 'index');
});

Solution 4:[4]

You can do this.

use App\Http\Controllers\ProfileController;

Route::controller(ProfileController::class)->group(function () {
  Route::get('/profile/{id}', 'show');
  Route::post('/profile/store', 'store'); 
});

Here is the documentation link: https://laravel.com/docs/8.x/routing#route-group-controllers

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 eriker75
Solution 4 Pri Nce