Dynamic CRUD Example with Repository Design Pattern in Laravel

Hello Artisan, hope you are doing very well. In this tutorial we are going to learn about repository design pattern and also we will see how we can use this repository design pattern in Laravel application. 

You will also learn what are the benefits of using the repository pattern laravel from this laravel repository tutorial. I will start from scratch and in this tutorial i will show you how we can create a complete crud application using this repository design pattern. 

I will use User model and create a simple crud operation using repository design pattern. You can get more benefit if you follow repository design pattern and write code to follow this pattern.

 

We can define it like 

Repository pattern is a kind of container where data access logic is stored. It hides the details of data access logic from business logic.

 

learn-how-to-use-repository-design-pattern-in-laravel

 

So let's start tutorial to create a complete dynamic crud application using repository design pattern. 

Step 1: Download Laravel

In this step we need to download a fresh laravel project as we will see it from scratch. So download it via below command if you have installed laravel installer in your machine.

laravel new rp

 

Step 2: Create Model and Migration

As we are going to use User model so no need to create model. Just setup database and migrate it to create crud application using repository pattern.

App\User

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];
   
    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function country()
    {
        return $this->hasOne(Country::class, 'user_id');
    }
}

 

Step 3: Create Repository Interface

As we are going to create a dynamic complete crud application using repository pattern so we we will create a interface like below where will put common behavior which is needed every where.

App\Repository\IUserRepository 

namespace App\Repository;

interface IUserRepository 
{
    public function getAllUsers();

    public function getUserById($id);

    public function createOrUpdate( $id = null, $collection = [] );

    public function deleteUser($id);
}

 

Step 4: Create Repository Class

Now we have to create our user repository class where we will override those function and wil will inplement those method. So create it like below.

App\Repository\UserRepository 

namespace App\Repository;

use App\User;
use App\Repository\IUserRepository;
use Illuminate\Support\Facades\Hash;

class UserRepository implements IUserRepository
{   
    protected $user = null;

    public function getAllUsers()
    {
        return User::all();
    }

    public function getUserById($id)
    {
        return User::find($id);
    }

    public function createOrUpdate( $id = null, $collection = [] )
    {   
        if(is_null($id)) {
            $user = new User;
            $user->name = $collection['name'];
            $user->email = $collection['email'];
            $user->password = Hash::make('password');
            return $user->save();
        }
        $user = User::find($id);
        $user->name = $collection['name'];
        $user->email = $collection['email'];
        return $user->save();
    }
    
    public function deleteUser($id)
    {
        return User::find($id)->delete();
    }
}

 

Step 5: Bind Repository in ServiceProvider

Now we have to bind this repository in our service provider. Now bind it like below.

App\Providers\AppServiceProvider

namespace App\Providers;

use App\Repository\IUserRepository;
use App\Repository\UserRepository;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(IUserRepository::class, UserRepository::class);
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        
    }
}

 

Step 6: Create Route

As we are going to create crud with repository pattern, so we have to create our route. so create it like below.

routes\web.php

Route::get('/users', 'UserController@showUsers')->name('user.list');
Route::get('/user/create', 'UserController@createUser')->name('user.create');
Route::post('/user/create', 'UserController@saveUser');
Route::get('/user/edit/{id}', 'UserController@getUser')->name('user.edit');
Route::put('/user/edit/{id}', 'UserController@saveUser')->name('user.update');
Route::get('/user/delete/{id}', 'UserController@deleteUser')->name('user.delete');

 

Step 7: Create Controller

Now in this step we have to create UserController to implement our all of the method to create a complete laravel php crud application using repository design pattern.

App\Http\Controllers\UserController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Repository\IUserRepository;
use Illuminate\Support\Facades\View;

class UserController extends Controller
{   
    public $user;
    
    public function __construct(IUserRepository $user)
    {
        $this->user = $user;
    }

    public function showUsers()
    {
        $users = $this->user->getAllUsers();
        $users->load('country');
        return View::make('user.index', compact('users'));
    }
    
    public function createUser()
    {
        return View::make('user.edit');
    }

    public function getUser($id)
    {
        $user = $this->user->getUserById($id);
        return View::make('user.edit', compact('user'));
    }
    
    public function saveUser(Request $request, $id = null)
    {   
        $collection = $request->except(['_token','_method']);

        if( ! is_null( $id ) ) 
        {
            $this->user->createOrUpdate($id, $collection);
        }
        else
        {
            $this->user->createOrUpdate($id = null, $collection);
        }

        return redirect()->route('user.list');
    }

    public function deleteUser($id)
    {
        $this->user->deleteUser($id);

        return redirect()->route('user.list');
    }
}

 

Step 8: Create Blade File

Everything are set to go. We have to just create our view then we can test our first repository pattern application with crud. So create view and paste this code in it.

resources/views/user/index.blade.php

 

resources/views/user/edit.blade.php

 

Now all are set to go. Now you can check it to visit this below url

 

URL
http://127.0.0.1:8000/users

 

Github Repository : Laravel Crud using Repository Design Pattern

 

Hope you have enjoyed this tutorial. If you like it please share this tutorial with your friends.

 

Facebook Github
A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using Laravel Vue and React Js Application.