What are disadvantages of using Eloquent or database queries in your Laravel controllers?
There are some reasons because of which you should not use Laravel controllers. First of all, you are breaking SOLID principles:
- Single Responsibility Principle — your controllers have extra responsibility of managing the database
- Dependency Inversion Principle — your controllers worry about how to persist data, instead of knowing when to persist it.
Also a couple of other principles like:
- DRY — as soon as you add more controllers / queue workers you will be copy — pasting the same logic everywhere
In general by bloating your controllers, you make your system more difficult to maintain (because of all this copy-pasta), it is not flexible (you cannot just refactor to use another persisting driver) and spaghetti code (because you are mixing the layer references).
When to use it?
Does it mean that using Laravel controllers is a big no, always? Well, no, not always. If you are an experienced developer and your only goal is to prototype something quick (like an experiment), then that would be perfectly fine. Maybe you just need to launch a service that is only collecting the data temporarily and there is a deadline pressure, then sure by all means you can do it.
Just be aware of the technical debt and tackle it as soon as experiment proved to be working.
Infrastructure Layer in Laravel
This is a place where you should place all your infrastructure logic. What is this logic? It is everything that connects with outside world like: other services, file system, database and everything that you Application does not ‘own’.
You should write your code the way that it abstracts away these means of ‘connection’ with external world. Therefore place all your Eloquent and database connection in this layer.