How to user the prefix route name

637 views Asked by At
Route::middleware(['auth', 'role:admin'])->name('admin.')->prefix('admin')->group(function(){
    Route::get('/role', [RoleController::class, 'index'])->name('index');
});

I want to user this route name. How I can?

              <li class="nav-item">
                <a href="{{ url('admin/role') }}" class="nav-link">
                  <i class="far fa-circle nav-icon"></i>
                  <p>Roles</p>
                </a>
              </li>

user as url and it's working but I want to user the route name

3

There are 3 answers

2
John Lobo On

Instead of url() method ,use route().Here admin refers to ->name('admin.') and index refers to ->name('index')

<a href="{{ route('admin.index') }}" class="nav-link">

Ref: URLs For Named Routes

route method parameters

/**
     * Generate the URL to a named route.
     *
     * @param  array|string  $name
     * @param  mixed  $parameters
     * @param  bool  $absolute
     * @return string
     */
    function route($name, $parameters = [], $absolute = true)
    {
        return app('url')->route($name, $parameters, $absolute);
    }
2
Christian Rosandhy On

You can use route() function to get url based on its name. Keep in mind that the prefix wont change the name defined in route, so in your case the name will be "index", not "admin.index"

<a href="{{ route('index') }}" class="nav-link">

But it will be better if you use a more detailed route name to prevent overlapped of route name, Example :

// no need to use name() in grouping level
Route::middleware(['auth', 'role:admin'])->prefix('admin')->group(function(){
    Route::get('/role', [RoleController::class, 'index'])->name('admin.index'); // set the complete name here
});

so you will be able to call them with this :

<a href="{{ route('admin.index') }}" class="nav-link">
0
Maaz Shahid On
Route::group(['prefix'=>'admin'], function(){

Route::resource('routename', ExampleController::class); });