(Laravel) How to use 2 controllers in 1 route?

2019-02-18 19:23发布

How can I use 2 controllers in 1 route?

The goal here is to create multiple pages with 1 career each (e.g: Accountants) then link them to a school providing an Accounting course.

An example page would consist of:
1. Accountants career information (I'm using a "career" controller here)
2. Schools providing Accounting courses (I'm using a separate "schools" controller here).

Route::get('/accountants-career', 'CareerController@accountants');
Route::get('/accountants-career', 'SchoolsController@kaplan');

Using the code above will overwrite 1 of the controllers.

Is there a solution to solve this?

2条回答
Lonely孤独者°
2楼-- · 2019-02-18 20:02

Is there a specific reason you need to use the same route name? Currently you have no way of telling the routes apart to laravel when it processes them.

why not something such as;

Route::get('/accountants/career', 'CareerController@accountants');
Route::get('/accountants/schools', 'SchoolsController@kaplan');

you could also do something like this if you have multiple careers going to the same controller and methods based on their value. This allows you to have a separate call you can call for each of your approved values rather than having to set a separate route and controller method for each.

Route::get('/{careerName}/career', 'CareerController@all');
Route::get('/{careerName}/schools', 'SchoolsController@kaplan');
查看更多
狗以群分
3楼-- · 2019-02-18 20:15

You cannot do that, because this is not a good thing to do and by that Laravel don't let you have the same route to hit two different controllers actions, unless you are using different HTTP methods (POST, GET...). A Controller is a HTTP request handler and not a service class, so you probably will have to change your design a little, this is one way of going with this:

If you will show all data in one page, create one single router:

Route::get('/career', 'CareerController@index');

Create a skinny controller, only to get the information and pass to your view:

use View;

class CareerController extends Controller {

    private $repository;

    public function __construct(DataRepository $repository)
    {
        $this->repository = $repository;
    }

    public function index(DataRepository $repository)
    {
        return View::make('career.index')->with('data', $this-repository->getData());
    }

}

And create a DataRepository class, responsible for knowing what to do in the case of need that kind of data:

class DataRepository {

    public getData()
    {
        $data = array();

        $data['accountant'] = Accountant::all();

        $data['schools'] = School::all();

        return $data;
    }

}

Note that this repository is being automatically inject in your controller, Laravel does that for you.

查看更多
登录 后发表回答