udoyen udoyen - 29 days ago 10
PHP Question

resolving laravel 5.3 route name conflict

I have this app in laravel 5.3 on my local machine that uses two

controllers



AdminUsersController and AgentUsersController


Now I set their
routes
in the following ways:

Route::group(['middleware' => 'admin'], function(){


Route::get('/admin', function(){
return view('admin.index');
});


Route::resource('admin/users', 'AdminUsersController');

Route::resource('admin/posts', 'AdminPostsController');
});


Route::group(['middleware' => 'agent'], function(){

Route::get('/agent', function(){
return view('agent.index');
});

Route::resource('agent/posts', 'AgentPostsController');

});


When I
list
the routes in this with
php artisan route:list
I get the following out come:

+--------+-----------+-------------------------+---------------+------------------------------------------------------------------------+--------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+-----------+-------------------------+---------------+------------------------------------------------------------------------+--------------+
| | GET|HEAD | / | | Closure | web |
| | GET|HEAD | admin | | Closure | web,admin |
| | GET|HEAD | admin/posts | posts.index | App\Http\Controllers\AdminPostsController@index | web,admin |
|
| | GET|HEAD | agent/posts | posts.index | App\Http\Controllers\AgentPostsController@index | web,agent |
| | POST | agent/posts | posts.store | App\Http\Controllers\AgentPostsController@store | web,agent |


Notice that the
URI agent/posts
has the
name
posts.index
and that the
URI admin/posts
has the
name
posts.index
.

Now in my
blade template
when I added the
route
for an
admin user
like so
{{route('posts.index')}}
. I get the
URI mydomain/agent/posts
instead of
mydomain/admin/posts
. How do I let
route
in
blade
know which of the
URIs
to pick.

I know I can also do
URL('/admin/posts')
to pick the right one, but I am wondering if using
route
method is possible.

Answer

Yes, you can override the names of one of your Resource controllers! Just pass another argument to the resource method, providing an array with the 'names' keyword as the index and another array as the value:

Route::resource('agent/posts', 'AgentPostsController', ['names' => [
    'index' => 'agent.posts.index'
]]);