DEV Community


Discussion on: Does repository pattern make sense when using it in Laravel?

aacsssh profile image
Aashish Ghale

In my understanding, this is not how Repository Pattern works. If you create a Repository class in Laravel then you should never return Eloquent models from that class because it makes your whole application depended on Eloquent. You may ask how?

By returning Eloquent models, we end up using many Eloquent related functions in our controllers or views. For example, if you want paginated data then you end up using LengthAwarePaginator's functions to get information like total pages, total data, current page and others. There are other scenarios which you may be well aware of if you are into Laravel.

What if in future for some reason, you want to ditch Eloquent and use other ORMs? You expect your application to run smoothly after the switch but it won't because your controllers and views are dependent on the functions that were provided via Eloquent. Your application is tightly coupled with Eloquent. Instead of returning Eloquent, you should return domain object. Please read "Patterns of Enterprise Application Architecture" by Martin Fowler for more information on this.

Saying all this, in my experience, I don't see any benefits of using Repository class in Laravel. I have not seen anyone ditching Eloquent in favour of other ORMs. If you have valid reason to switch then repository pattern may help but you have to design it well at first.

If you are sticking with Eloquent then why add an extra layer? If you really want a place where you can create nice APIs for long queries that requires multiples query builder functions then you can define it in model itself by astracting the methods in a trait and using it model and use it in some Service class accordingly.