Repositories

Introduction

We created an open source package with our implementation of the [repository pattern](https://github.com/PropaySystems/laravel-base-repositories). This gives you a lot of boilerplate so you write less code. You will need to be disciplined to use the functions correctly and stick to your standards.

This keeps your controllers lean and moves your domain logic to the service classes, with your database logic and queries in the repository classes. For instance, you add a register method to your UserService and can then use the same logic to register a user from a controller, command, job, etc., which links back to the DRY principle.

Best practice is to create a repository class for each model, and you can import all the repository classes you need into the services. Service classes should also not be very long: if there are more than 10 methods in a class, consider creating a separate class. (This is all up to the developer — if the functions are related to the class, keep them together.)

You should NOT query models directly in your code, queries should be done in the repositories.

Repository Pattern

From the package you can see that the folder structure for the pattern uses the standard Laravel locations for adding extra functionality. Repositories will be added in the base directory of \App\Repositories and services will be added in the base directory of \App\Services. You are free to change the directories in the config file of the package.

Create Service class

php artisan base:create Users/User -s

This will create the UserService class in the Services directory \App\Services\Users\UserService.

Create Repository class

php artisan base:create Users/User -r --model=App/Models/Users/User

This command will create the repository files in \App\Repositories\Users\UserRepository\Interface\UserRepositoryInterface & \App\Repositories\Users\UserRepository.

Specifying the model in this command will automatically link the relevant model class to the repository, the model will automatically be injected in the construct method of the class. Each model class needs its own repository files; this links back to the Single Responsibility Principle, keeping each class to a single responsibility.

Create Service & Repository classes at the same time.

php artisan base:create Users/User -s -r --model=App/Models/Users/User

This will automatically create a RepositoryProvider::class and link it to Laravel to register the repositories and interfaces together.

These custom repository classes automatically extend the BaseRepository classes so that you have access to prebuilt functions like create, update, delete, firstOrCreate, all, find, findBy, findOneBy etc, this is very useful and reduces the amount of code you need to write for the basic operations you perform on most models.

Copyright © 2026