I got too many SQL queries in the controller. In the sense, the queries themselves are not so many, but they are rather long. I think about where it would be better to take them out of the controller. Maybe create a model of the page and put it there?

Only kindly request - do not respond in an abstract way like "this can be done in a variety of ways, and not count them all." Please suggest a specific solution that you consider to be the best.

I especially liked this example of the organization of the model proposed at Laracasts :

app /myApp (or project) /posts (post example, but same for all product features, Users, etc. I remove directories that are not relevant) /repository /contracts /commands /services /exceptions /events /documentation (I like to keep project documentation in the relevant areas vs centralized ) /middleware Abstract class Post.php (model) PostManager.php (management code) 

I still do not fully understand the purpose and features of all these elements of the model, but I would like to understand.

  • It is difficult to offer something concrete without seeing the essence of the discussion ... What are the queries, what are they related to, what complexity, what models or entities are obtained as a result? - Daniel Protopopov

2 answers 2

In fact, if we talk about SOLID , then the model also should not contain query logic, since class 1 implies one responsibility, which by the way is the ActiveRecord pattern that Eloquent uses actively violates - by introducing methods to the model for database queries and not only. In general, if you do not care about technical debt, maintainability of the code and its testability, you can leave requests to controllers or models. If SOLID architecture is important to you, then I recommend adding a repository layer that will encapsulate the database query logic. Here, for example, is a good package for Laravel for the implementation of repositories - https://packagist.org/packages/prettus/l5-repository , if you do not want to write it yourself. Again, if we talk about convenience, usually the controllers are thin, leaving a minimum of code in them, all business logic goes to Services or Commands (depends on the adopted application architecture), work with the base goes to Repositories , Models or Entities only for the narrative (well, since Eloquent insists, then mutators / casters are written in them and this is all)

    If there is a couple of lines there is no need, if there are complex samples, conditions, filters, sorting, etc., then it is better to carry it into the model so as not to clutter up the controller. There should be a minimum of functionality in controllers, all logic should be in models or in services. All logic regarding the database is in models