The Repository pattern.
Repositories are classes or components that encapsulate the logic required to access data sources.
They centralize common data access functionality, providing better maintainability and decoupling the infrastructure or technology used to access databases from the domain model layer.
The basic difference between model and Repository are
Models allow you to query for data in your tables, as well as insert new records into the table. What this is saying, is a Model opens access to a database table. It also allows you to relate to other models to pull out data without having to write individual queries.
A repository allows you to handle a Model without having to write massive queries inside of a controller. In turn, keeping the code tidier, modular and easier to debug should any errors arise.
Example
You could use a repository in the following way:
public function makeNotification($class, $title, $message)
{
$notification = new Notifications;
...
$notification->save();
return $notification->id;
}
public function notifyAdmin($class, $title, $message)
{
$notification_id = $this->makeNotification($class, $title, $message);
$users_roles = RolesToUsers::where('role_id', 1)->orWhere('role_id', 2)->get();
$ids = $users_roles->pluck('user_id')->all();
$ids = array_unique($ids);
foreach($ids as $id) {
UserNotifications::create([
'user_id' => $id,
'notification_id' => $notification_id,
'read_status' => 0
]);
}
}
controller:
protected $notification;
public function __construct(NotificationRepository $notification)
{
$this->notification = $notification;
}
public function doAction()
{
...
$this->notification->notifyAdmin('success', 'User Added', 'A new user joined the system');
...
}
The repository pattern consists of adding an abstraction layer between the data access layer and the business logic layer of an application that are in charge of accessing the data source and obtaining the different data models. It is a data access pattern that prompts a more loosely coupled approach to data access
We are Recommending you:
- Laravel remove public from url
- Laravel 8 multi auth login
- Laravel 8/7 Overwriting the Default Pagination System
- How to use soft delete in Laravel?
- How to create real time sitemap.xml file in Laravel
- Laravel Command List
- Laravel 8 .htaccess file for php 8
- Laravel's .htaccess to remove "public" from URL
- Custom 404 Page In Laravel 8
Step Out of Your Comfort Zone: 10 Powerful...
Is Mobile Reels Harming Our Children? Here's...
Simple body language tricks1. Stand with...
Best Free Websites to Learn CodingIf you...
Zip is a command-line utility tool used for...
1. What is database?A database is a...
ParameterDescriptionto Required. Specifies...
Best Free Websites to Learn CodingIf you...
You can create your custom 404 page...