Julian Mendez
Julian Mendez

Reputation: 3380

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?

Upvotes: 0

Views: 90

Answers (2)

user7744592
user7744592

Reputation:

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

Upvotes: 1

Omniremo
Omniremo

Reputation: 1

It has always worked best for me to have a controller per resource type. You have the resource 'foo' with FooController, and 'bar' with BarController. So for the root context resource, you aught to have a root controller.

This helps with separation of concern and keeps your code modularized.

Upvotes: 0

Related Questions