Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - multiple resource routes to single controller with argument

Can we have a single controller for multiple routes, and get the parameter?

Currently, I have these routes:

Route::resource('/customers', 'CustomerController');
Route::resource('/agents', 'AgentController');

And a CustomerController and a AgentController with all resource functions working.

But as CustomerController and AgentController are almost same except for one database field, i.e. group_id. I was thinking to use one controller i.e. PartyController and one route as:

Route::resource('/parties/customers', 'PartyController ');
Route::resource('/parties/agents', 'PartyController ');

or if someone suggests:

Route::resource('/parties/{group}', 'PartyController ');

I have been searching for a while but finding it hard to follow this path. I've added this code in the constructor of PartyController, to check the calling route:

    $path = Request::capture()->path();
    $this->group = ucwords(explode("/", $path)[1]);
    echo($this->group );

All seems to be going well till here. But when in my index.blade.php, I have this statement:

<p>{{ link_to_route('parties.create', 'Add new') }}</p>

I get an exception:

Route [parties.create] not defined. 

I've tried multiple combinations, without any success and more errors come through, like accessing /parties/customers/create doesn't work now.

So, is it possible anyway or should I abandon this idea?

EDIT: My question is different from Same Laravel resource controller for multiple routes as I am not using a trait.

like image 622
MJ Khan Avatar asked Dec 10 '22 09:12

MJ Khan


1 Answers

If I were you, I would use:

Route::resource('/customers', 'CustomerController');
Route::resource('/agents', 'AgentController');

Now you can make AgentController extending CustomerController (or any other controller you want) so they can reuse same code. If needed you can set in constructor some properties for example group to know if you are dealing with agents or customers.

To make your routes working you can pass extra variable from controller to view, to have in your blade:

<p>{{ link_to_route($group.'.create', 'Add new') }}</p>
like image 178
Marcin Nabiałek Avatar answered Dec 28 '22 22:12

Marcin Nabiałek