How to use Repositories in Laravel Framework, so as not to repeat code

One of the big problems in software development is code repetition, which adds a lot of difficulties when it comes to project maintenance.

There is a concept in software development called DRY (The Don't Repeat Yourself), this concept proposes that you do not repeat your code, if you need to do the same action, in more than one place in your project, you must create an abstraction for that.

To apply the DRY concept in the Laravel framework, there are some architectures developed by the community, today we are just going to talk about Repositories.

Imagine the following scenario, you have a system where the user can register alone to have access to a logged-in area, but someone who is already registered in the system can also invite that same user through an invitation.

It's not hard to see that you'll need two codes to register a user, one outside the application and one inside.

Well, to solve this kind of situation, we will use a Repository called "UserRepository.php"

User repository

UserRepository.php is an abstraction that we can call wherever we like.

In our example, we will have two controllers, RegisterController.php (for external registers) and UsersControllers.php (for internal registers).

As you can see, I can call UserRepository.php from both controllers and I'm not repeating myself.

Register Controller

I can also make the same call from the UsersController.php controller


This way, you can make your software maintenance much simpler and more efficient.

Because when you need to fix a bug or implement a new feature, you know you only need to edit UserRepository.php

Repositories also serve to facilitate cache reprocessing, imagine that you redo the user cache using several different methods of your application, with repositories that you will always call from the same method.