Should ORM calls be inside a model or controller?

I am using Laravel, with Eloquent, the default ORM.

The documentation mentions the fact that ORM calls in the controller are fine, but that doesn't fit.

For example, let's say I want to get a user. User::findOrFail($id)

is the code I need. the documentation has this inside the Controller.

Imagine I have this bit of code in 100 locations throughout the project and I need to hang it up again, perhaps to get a user who also has a flag against their account. It's a bit of a hassle, but whether it was in the model I would just update the model method.

An example of an example method in this case:

function get_user_by_id($id)
{
    return User::findOrFail($id);
}

      

The downside to this is that the models will soon be huge.

So what's the best thing here?

+3


source to share


1 answer


Where should you place?

Ask yourself if you need to encapsulate this piece of code. If you answer yes, put it in the model. Otherwise, go ahead and call it from the controller.

Will they be too big?



Elegant models already include so much functionality because the ORM uses an active record template, not data like Doctrine. Therefore, your models probably won't get too big as many functions are already inherited and you rarely have to write your own.

Will you be happier with more control over your structure?

If you are too concerned about the structure of the database layer and want to apply the concern principle separation to heart, use Doctrine instead. So you will be better. But I really think Eloquent should be fine in most cases.

0


source







All Articles