Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...