Repository pattern in laravel with crud example

Last updated : Mar 25, 2023

This article explains you about repository pattern in laravel with crud example.

There are many design patterns available for programmers in Laravel which they can use to make coding a good experience and build complex apps easily.

One of these design patterns is known as `Repository pattern`. We will explain each design pattern in Laravel in future articles.

Repository pattern:

In this design pattern the data source layer is abstracted with another layer called repository. This abstraction uses dependency injection and separates data source layer with business layer in an application. Because of this repository layer the data model does not know and does not have anything to do with data source layer.

Let's see the practical picture of Repository pattern in Laravel with crud example.

First create a directory Repos in app\Http directory. And another directory RepoInterfaces in Repos directory.

Then in the RepoInterfaces directory, create a file named UserRepoInterface.php. Code the following:

<?php

    namespace App\Http\Repos\RepoInterfaces;

    interface UserRepoInterface {
        public function getUsers();

        public function getUserById($data);
        
        public function saveUser($data);

        public function updateUser($data);
        
        public function deleteUser($data);
    }

Then in the Repos directory, create a file named UserRepo.php. Code the following:

<?php

    namespace App\Http\Repos;

    use App\Models\User;
    use App\Http\Repos\RepoInterfaces\UserRepoInterface;
    use Illuminate\Support\Facades\Hash;

    class UserRepo implements UserRepoInterface {
        
        public function getUsers(){
            $response_data = User::orderBy('id')->get();
            return $response_data;
        }

        public function getUserById($data){
            $response_data = User::where('id',$data->id)->first();
            return $response_data;
        }
        
        public function saveUser($data){
            $pass = "dummypassword";
            $new_id = User::insertGetId([
                'name' => $data->name,
                'email' => $data->email,
                'password' => Hash::make($pass)
            ]);
            return $new_id;
        }

        public function updateUser($data){
            
            $response_data = User::where('id', $data->id)
            ->update([
                'email' => $data->email,
                'password' => Hash::make($data->password)
            ]);
            return $response_data;
        }
        
        public function deleteUser($data){
            $response_data = User::where('id', $data->id)
            ->delete();
            return $response_data;
        }

    }

Then in the Controllers directory, create a file named UserController.php. Code the following:

<?php
    
    namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use App\Http\Repos\UserRepo;

    class UserController extends Controller
    {
        private $user_repo;

        public function __construct(UserRepo $user_repo){
            $this->user_repo = $user_repo;
        }

        public function getUsers(){
            return response()
            ->json($this->user_repo->getUsers());
        }

        public function store(Request $request){
            return response()
            ->json($this->user_repo->saveUser($request));
        }

        public function show(Request $request){
            return response()
            ->json($this->user_repo->getUserById($request));
        }

        public function update(Request $request){
            return response()
            ->json($this->user_repo->updateUser($request));
        }
    
        public function destroy(Request $request){
            return response()
            ->json($this->user_repo->deleteUser($request));
        }
    }

Finally bind this interface with implementation. For this head towards app\Providers\AppServiceProvider.php file. At top of file before class code import interface file and implementation file.

use App\Http\Repos\RepoInterfaces\UserRepoInterface;
use App\Http\Repos\UserRepo;

And in the register method, add following line of code.

$this->app->bind(UserRepoInterface::class, UserRepo::class);

As you saw in UserController script, the script was concise, clear and short. The advantage that this pattern provides is that you can change the implementation in controller without changing any other line of code.

Note: It is not considered best practice to create only one repository for common implementations. You should create 1 interface for each model. But in rare cases you have to maintain same interface for multiple classes.

For example in Laravel itself when in .env file, if you have mentioned mysql database credentials then it changes the implementation to mysql class and changes according to any other database. But it connects with only one database at a time.

So if you use multiple implementations then you can get data from request or config file to decide which implementation to bind. You can code this in register method in AppServiceProvider.php file.

That is it for repository pattern with crud example in Laravel. After understanding this process, you can modify this application completely and can create whatever the requirement is.



Sign in for comment. Sign in