Organizing code is always hard, especially Models. When you are reading Laravel documentation it can be a bit misleading. It is easy to follow, but it doesn’t mention how to organize your code. Those who are programming for several years should already know all the things that will be said in this article.
Usually most MVC frameworks have 3 folders: Models, Views and Controllers. In Laravel 5 Taylor removed Models folder. He thought that people are misusing it. In my opinion he made an error. Those who know how to organize code - will organize it. And those who don’t - they will use the default settings (models are generated in app/ folder).
So the main question you should have: What is model in MVC?
Let’s look at 3 ways how Eloquent can be used.
1. Fast and Dirty
Easiest way to write code is to put it directly in Controller. It is used for simple code where there is not much logic. Let’s take a simple blog example. You can create post and later you can publish it to be visible to everybody.
This code is simple, fast to write and best suited when you are making simple things. When you logic becomes more complicated it can quickly become spaghetti code.
When doing things this way, your Eloquent Post class doesn’t contain any logic.
This time we will move all the logic into Eloquent class. Now controller code is simpler.
This way of doing things is optimal. It removes your logic from controller and moves it into the model.
But there is one small disadvantage, you can still call Eloquent methods in Controller:
Of-course I know that I shouldn’t do like this if I chose the second method. But new developer can easily do that.
3. Clean and Slow
This method sometimes is called Service pattern. It is mostly used for objects that have a lot of complex logic. Controller will be totally separated from Eloquent. We will need one more file for that. But let’s look at the controller first.
I have created new plain PHP class and called it BlogPost. Controller can access only BlogPost class methods. Now controller doesn’t know about Eloquent existence.
BlogPost class now contains all the logic. It also directly talks to Eloquent Post class. The most important thing is that BlogPost doesn’t extend anything.
Eloquent Post class is left empty. You can still use it for relationships and scopes.
Another question you might have is where to put your classes?
For the 1 and 2 examples I would put Post class in Models folder
For the 3 example, file structure will look like this:
Models folder file structure is similar to how /vendor folder is organized. Usually you have one main file per package that you can access. All other package files doesn’t matter to you. So in my opinion Models folder should be structured the same way.
First method is usually used for small projects. Third method is used when you don’t want Eloquent to leak into your controller.
I am mostly using 1 and 2 methods. 3 method is used quite rarely in my code.