latenight
latenight

Reputation: 155

Is there any way to use one route with two controller in Laravel?

I want one route with two controllers. However, I can't implement it. I have ExpenseController and IncomeController and my route looks like this:

Route::get('/api/expense/', 'ExpenseController@index');
Route::post('/api/expense', 'ExpenseController@create');

And I want to add the same route with IncomeController

Route::get('/api/expense', 'IncomeController@index');
Route::post('/api/expense', 'IncomeController@create');

Upvotes: 1

Views: 2863

Answers (1)

JorisJ1
JorisJ1

Reputation: 989

No, It is not possible to directly link one route to two controllers.

However, in the comment section is determined that there is no actual need for one route to link to multiple controllers, but rather a single controller that controls multiple models.

You could create a single controller BudgetController that controls both incomes and expenses. Here is an example for showing a list of both on the same page:

routes/web.php

Route::resource('budget', 'BudgetController');

app/Http/Controllers/BudgetController.php

public function index() 
{
    return view('budget.index', [
        'incomes' => Income::all(),
        'expenses' => Expense::all(),
    ])
}

resources/views/budget/index.php

<table>
    @foreach($incomes as $income)
        <tr><td>{{ $income->amount }}</td></tr>
    @endforeach
</table>

<table>
    @foreach($expenses as $expense)
        <tr><td>{{ $expense->amount }}</td></tr>
    @endforeach
</table>

Upvotes: 1

Related Questions