简体   繁体   中英

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');

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM