Home > OS >  Route Name Prefix: Why can't I use "admin.home" in Laravel 9 in grouped routes?
Route Name Prefix: Why can't I use "admin.home" in Laravel 9 in grouped routes?

Time:01-30

Route::group(['controller' => AdminController::class, 'prefix' => 'admin', 'as' => 'admin.'], function () {
    Route::get('/', 'index')->name('home');
});

This is what I'm using, based on about 20-25 searches it should work, so I should be able to reach a route by using route('admin.home') in blade. However it says that admin.home is not defined.

Why is "as" nor the "prefix" not working? I honestly don't get it, I literally copy-pasted an "accepted answer"'s code and it still doesn't work...

CodePudding user response:

Solution

Route::name('admin.')
    ->controller(AdminController::class)
    ->prefix('admin')
    ->group(function () {
        // Matches the "/admin" URL
        // with route name "admin.home" 
        // pointing to AdminController::index(...) method.
        Route::get('/', 'index')->name('home');
    });

Reference(s)

  1. Route Name Prefixes

The name method may be used to prefix each route name in the group with a given string. For example, you may want to prefix all of the grouped route's names with admin. The given string is prefixed to the route name exactly as it is specified, so we will be sure to provide the trailing . character in the prefix:

Route::name('admin.')->group(function () {
    Route::get('/users', function () {
        // Route assigned name "admin.users"...
    })->name('users');
});
  1. Controllers
Route::controller(OrderController::class)->group(...);
  1. Middleware
Route::middleware(['first', 'second'])->group(...);
  1. Route Prefixes
Route::prefix('admin')->group(...);
  1. Route Groups
Route::group(...);

Addendum

Clear/refresh your route cache if cached previously:

Terminal Command:

php artisan route:clear

  • Related