CRUD Example with Repository Design Pattern in Laravel

tutspack laravel
Spread the love
  • 188
  •  
  •  
  •  
  •  
  •  
  •  
    188
    Shares

Hello Atrisans,

How are you doing? In this tutorial, I will discuss with you what is repository design pattern and show you how to implement repository design pattern in you laravel application. If you don’t know about repository pattern, don’t worry I will explain everything. so here we go.

Repository pattern is a kind of container where data access logic is stored. It hides the details of data access logic from business logic. So let’s start a tutorial to create a complete dynamic CRUD application using repository design pattern. 

Step 1: Install Laravel via Composer

In this step, we need to download a fresh laravel project as we will see it from scratch. To install Laravel via Composr run the below command.

composer create-project laravel/laravel laravel_repository

Step 2: Create Model and Migration

Now we have to Create a Model as well a migration file. Run this command in your terminal.

php artisan make:model Student -m

Then go to the migration file which you have created by previous command.

database/migrations/2021_01_23_093000_create_students_table.php 

   public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('roll');
            $table->timestamps();
        });
    }

Now run.

php artisan migrate

App\Models\Student

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', 'roll'
    ];
   
}

Step 3: Create Repository Interface

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

App\Repository\Student\StudentInterface 

<?php

namespace App\Repository\Student;

use App\Models\Student;

interface StudentInterface{
    public function getAllData();
    public function storeOrUpdate($id = null,$data);
    public function view($id);
    public function delete($id);
}

Step 4: Create Repository Class

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

App\Repository\Student\StudentRepository 

<?php

namespace App\Repository\Student;
use App\Models\Student;
use function is;
use function is_null;

class StudentRepository implements StudentInterface{
    public function getAllData(){
        return Student::latest()->get();
    }

    public function storeOrUpdate($id = null,$data){
        if(is_null($id)){
            $student = new Student();
            $student->name = $data['name'];
            $student->roll = $data['roll'];
            return $student->save();
        }else{
            $student = Student::find($id);
            $student->name = $data['name'];
            $student->roll = $data['roll'];
            return $student->save();
        }
    }

    public function view($id){
        return Student::find($id);
    }
    public function delete($id){
        return Student::find($id)->delete();
    }
}

Step 5: Bind Repository in ServiceProvider

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

App\Providers\AppServiceProvider

<?php

namespace App\Providers;

use App\Repository\Student\StudentInterface;
use App\Repository\Student\StudentRepository;
use App\Repository\User\UserInterface;
use App\Repository\User\UserRepository;
use Illuminate\Support\ServiceProvider;

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

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}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);
    }
}

Step 6: Create Route

As we are going to create a CRUD with repository pattern, so we have to create our route. so create routes like below.

routes\web.php

Route::name('student.')->prefix('student')->namespace('Student')->group(function (){
    Route::get('index','StudentController@index')->name('index');
    Route::post('store','StudentController@storeOrUpdate')->name('store');
    Route::get('view/{id}','StudentController@view')->name('view');
    Route::put('update/{id}','StudentController@storeOrUpdate')->name('update');
    Route::get('delete/{id}','StudentController@delete')->name('delete');
});
Also Read : CRUD with Sanctum

Step 7: Create Controller

Now in this step, we have to create StudentController to implement our all of the method to create a complete laravel CRUD application using repository design pattern. Run this command in your terminal.

php artisan make:controller Student\StudentController

App\Http\Controllers\Student\StudentController.php

<?php

namespace App\Http\Controllers\Student;

use App\Http\Controllers\Controller;
use App\Models\Student;
use App\Repository\Student\StudentInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use function is_null;
use function redirect;

class StudentController extends Controller
{
    protected $student;
    public function __construct(StudentInterface $student)
    {
        $this->student = $student;
    }

    public function index(){
        if(View::exists('student.index')){
            return \view('student.index',[
                'students' => $this->student->getAllData(),
                'trashed' => $this->student->getAllTrashedData()
            ]);
        }
    }

    public function storeOrUpdate(Request $request,$id = null){
        $data = $request->only(['name','roll']);
        if(!is_null($id)){ //update
            $this->student->storeOrUpdate($id,$data);
            return redirect()->route('student.index')->with('message','Data Updated!');
        }else{//insert
            $this->student->storeOrUpdate($id = null,$data);
            return redirect()->route('student.index')->with('message','Data Inserted!');
        }
    }

    public function view($id){
        if(View::exists('student.edit')){
            return view('student.edit',['student' => $this->student->view($id)]);
        }
    }

    public function delete($id){
        $this->student->delete($id);
        return redirect()->route('student.index')->with('message','Data Deleted!');
    }
}

Step 8: Now 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/student/index.blade.php

@extends('layouts.master')
@section('title' ,'Home')
@section('main_content')
    <div class="row">
        <div class="col-12">
            <h1 class="text-center">Repository Design Pattern CRUD</h1>
            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
                Add New Data
            </button>
            <hr>
            <table class="table table-bordered">
                <thead>
                <tr>
                    <th>SL</th>
                    <th>Name</th>
                    <th>Roll</th>
                    <th>Actions</th>
                </tr>
                </thead>
                <tbody>
                @forelse($students as $key => $student)
                    <tr>
                        <td>{{++$key}}</td>
                        <td>{{$student->name}}</td>
                        <td>{{$student->roll}}</td>
                        <td>
                            <a href="{{route('student.view',$student->id)}}" class="btn btn-sm btn-info">Edit</a>
                            <a href="{{route('student.delete',$student->id)}}" class="btn btn-sm btn-danger">Trash</a>
                        </td>
                    </tr>
                @empty
                @endforelse
                </tbody>
            </table>
@stop

edit.blade.php

 
@extends('layouts.master')
@section('title' ,'Edit')
@section('main_content')
    <div class="row justify-content-center">
        <div class="col-6">
            <h2 class="text-center">Edit Student</h2>
            <hr>
            <form action="{{route('student.update',$student->id)}}" method="post">
                @csrf
                @method('PUT')
                <div class="form-group">
                    <input type="text" class="form-control" name="name"value="{{$student->name}}">
                </div>
                <div class="form-group">
                    <input type="text" class="form-control" name="roll" value="{{$student->roll}}">
                </div>
                <div class="form-group">
                    <button class="btn btn-block btn-success">Add New Data</button>
                </div>
            </form>
            <a href ="{{route('student.index')}}" class="btn btn-block btn-info">Back</a>
        </div>
    </div>
@stop

Now Run php artisan serve then hit http://127.0.0.1:8000/index

Hope this tutorial will help you.

Github : https://github.com/AR-Shahin/laravel-crud-using-repository-design-pattern

Read : 10 PHP interview question

Spread the love
  • 188
  •  
  •  
  •  
  •  
  •  
  •  
    188
    Shares
  • 188
    Shares

About Anisur Rahman Shahin

Hello. My name is Shahin. I'm a tech enthusiast guy. Personally, I’m Optimistic and always in hurry kinda person. I'm a freelance web developer. I am working at Zakir Soft as Laravel Developer. My Portfolio website: https://devshahin.com/

View all posts by Anisur Rahman Shahin →

4 Comments on “CRUD Example with Repository Design Pattern in Laravel”

Leave a Reply

Your email address will not be published. Required fields are marked *