简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM