Home > OS >  How can I use similar routes with different namespaces in Laravel 8?
How can I use similar routes with different namespaces in Laravel 8?

Time:08-07

I have a problem with routes in Laravel 8.
I have 2 controllers with the same controller name and same function name but in different namespaces.

Route 1:

Route::namespace('Frontend')->group(function () {

    //Frontend Category Route
    Route::get('{main}/{slug}', 'CategoryController@one')->name('category.1');

});

Route 2:

Route::namespace('Backend')->group(function () {

    //Backend Category Route
    Route::get('categories/{level?}/{id?}', 'CategoryController@index')->name('categories');

});

Namespace line of Category Controller in Frontend:

namespace App\Http\Controllers\Frontend;

Namespace line of Category Controller in Backend:

namespace App\Http\Controllers\Backend;

When I call "index" function in backend category controller the function named "one" in frontend category controller works.

Is there any solution other than changing the controller name?

PHP Version: 7.3.10
Laravel Version: 8.83.13

CodePudding user response:

You could prefix both route groups like this:

  /* --- Frontend --- */
  Route::prefix('/backend')->namespace('Backend')->group(function(){
    Route::get('categories/{level?}/{id?}', 'CategoryController@index')->name('categories');
  });

  /* --- Frontend --- */
  Route::prefix('/front')->namespace('Frontend')->group(function(){
    Route::get('{main}/{slug}', 'CategoryController@one')->name('category.1');
  });

If you don't want to prefix the "front" routes, just put the backend routes on top. Backend routes will be evaluated first and if there's no match, the requested url will fall to the frontend routes.

  • Related