Hello Artisan,
In this tutorial, I will show you a complete example of the Laravel 9 repository pattern. You know that The main idea of using Repository Pattern in a Laravel application is to create a bridge between models and controllers. In this laravel 9 repository pattern example, you will see a complete crud example with repository pattern in Laravel 9.
Before using a repository pattern in Laravel, the question is, why do you use a repository pattern in laravel? Cause repository pattern gives us a bridge between models and controllers. We can reuse the code which we write inside the repository in any controller by using dependency injection.
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.
See let's see a complete laravel repository pattern crud example step by step. So let's start the tutorial to create a complete dynamic crud application using a 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 the below command if you have installed laravel installer on your machine.
laravel new rp
Step 2: Create Model and Migration
As we are going to use the User model so no need to create a model. Just set up a database and migrate it to create a 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 will create an interface like below that will put common behavior which is needed everywhere.
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 functions and will implement that 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 to 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 a 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 all of the methods to create a complete laravel php crud application using the 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 is set to go. We have to just create our view then we can test our first repository pattern application with crud. So create a view and paste this code into 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 the below URL
Below the GitHub repository of this tutorial, you can download it from the below URL:
Github Repository : Laravel Crud using Repository Design Pattern
Read also: Upload Large CSV File using Queue Job Batching in Laravel
Hope you have enjoyed this tutorial. If you like it please share this tutorial with your friends.
#laravel #laravel-9x