advantage of repository pattern in laravel against instantiating a model in a controller constructor advantage of repository pattern in laravel against instantiating a model in a controller constructor laravel laravel

advantage of repository pattern in laravel against instantiating a model in a controller constructor


It really comes down to how you have set-up your code. In your particular case, there wouldn't appear to be much benefit.

But what if your code required you to have multiple instantiations of your model across many different controllers? For example, maybe you have a model to your user repository. There may be many controllers which need to get information about the user.

Then it would be a hassle to go through all your controllers changing all the references (i.e. your example 2). Much better to just change the repository once (i.e. your example 1).

There is never one size fits all in coding. The best you can do is code for what you need now, with an awareness of any potential solutions which may aid flexibility in the future. My view is that the repository pattern is one of those solutions which aids flexibility. You may never need to change the model, or move to a different database, but the effort in coding with it now is minimal compared to the hassle you will have if you ever did want to change your db.


Being prepared for switching databases is one of the most annoying arguments one can give for the repository pattern. This one is usually followed by the ignorant "I'll never switch databases." If i had an upvote for each time I had this conversation...

Now imagine you want to add a back-end like caching or some search engine to optimize searches. This would fit really well in a repository pattern.

The general key benefit of the repository pattern is that all changes related to the back-end are more manageable than otherwise.

To demonstrate why you wouldn't want this stuff in a model; If you want to migrate a model's attributes the model needs to be fetched from the back-end differently. You might need two models in some cases. When you have this all in one model you need to apply a lot of hackery to make this even work. If the repository manages these changes the models stay clear and your code becomes manageable again.