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

牧云@^-^@ 提交于 2019-11-27 07:24:04

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/26091998/laravel-how-to-use-2-controllers-in-1-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!