Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...