Custom repository pattern in Laravel 5.4

Custom repository pattern in Laravel 5.4

Custom repository pattern in Laravel 5.4 ,Why do we want to use some packages and want to increase page load time. Lets create simple repository pattern by own in laravel 5.4. Lets see how to create repository pattern.

Step 1 : Create Repository Interface

My folder structure is : App\Contracts\Repository


Step 2 : Create BaseRepository which implements Repository interface

My Folder Structure is  : App\Repositories


Step 3 : Create Artisan Command and Stubs to make custom artisan command. By running this artisan command you can create a repository file

Create Commands folder under App\Console :

Create MakeRepositoryCommand.php inside commands folder Which will help to create artisan command


make:repository {name} // Usage example : php artisan make:repository ExampleRepository => It will create a ExampleRepository.php under Repositories folder.
getStub() It will get dummy file from given path and create a file based on artisan command

Create repository.stub folder under Commands\stubs\repository.stub


//DummyClass Will replace with artisan Repository Name.

Now Run ” php artisan ” in terminal it will show php artisan:make repository command.

Repository pattern

Example and Usage : run php artisan make:repository ExampleRepository in termianl

Your ExampleRepository.php looks like below : Here inject your model.


How to Inject Repository  Pattern in controller


Thats it now you have created repository pattern for your model.

You can create and inject individual repository pattern for each models by running php artisan make:repository command.

Hope it will help someone.