DEV Community

Cover image for How to use Repositories in Laravel Framework, so as not to repeat code
Paulo Castellano
Paulo Castellano

Posted on • Originally published at paulocastellano.com

3 1

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"

UserRepository - Laravel

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.

RegisterController - Laravel

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

UsersControler - Laravel

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay