Search code examples
laravelmodel-view-controllercontrollers

Controllers design pattern


I have a design question about MVC and controllers

I have this two routes

Route::get('/foo/{id}', FooController@show)
Route::get('/bar/{id}', BarController@show)

But know, I would like to add another route for the index like this

Route::get('/', ???)

In this route, I need some information about the Foo and Bar models. The question is, should I create a new controller for that route? like MainController?


Solution

  • In general, controllers are meant to respond to requests associated with a specific resource (model). Thereby, given your concrete example, two distinct scenarios apply.

    1. The Foo and Bar models are required on the landing page (/ route): In this case, a dedicated controller would be a perfectly fine thing to do. Also, the use of a view model would be beneficial.
    2. No information about application-specific models is needed on the landing page: You can still use a dedicated controller class to return your view, while another possibility would be the use of a lambda function:

      Route::get('/', function () {
          return view('landing');
      });