All Projects → illuminatech → db-safedelete

illuminatech / db-safedelete

Licence: other
Attempts to invoke force delete, if it fails - falls back to soft delete

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to db-safedelete

laravel-boolean-dates
Automatically convert Eloquent model boolean attributes to dates (and back).
Stars: ✭ 31 (+93.75%)
Mutual labels:  eloquent, model
Befriended
Eloquent Befriended brings social media-like features like following, blocking and filtering content based on following or blocked models.
Stars: ✭ 596 (+3625%)
Mutual labels:  eloquent, model
Plans
Laravel Plans is a package for SaaS apps that need management over plans, features, subscriptions, events for plans or limited, countable features.
Stars: ✭ 326 (+1937.5%)
Mutual labels:  eloquent, model
laravel-route-model-autobinding
THIS PACKAGE HAS BEEN DEPRECATED — Automatically bind Eloquent models as route segment variables.
Stars: ✭ 14 (-12.5%)
Mutual labels:  eloquent, model
Schedule
Schedule is a package that helps tracking schedules for your models. If you have workers in a company, you can set schedules for them and see their availability though the time.
Stars: ✭ 155 (+868.75%)
Mutual labels:  eloquent, model
laravel-geoly
Perform fast and efficient radius searches on your Laravel Eloquent models.
Stars: ✭ 25 (+56.25%)
Mutual labels:  eloquent, model
Laravel Model Status
Easily add statuses to your models
Stars: ✭ 510 (+3087.5%)
Mutual labels:  eloquent, model
laravel-loggable
🎥 📽 🎞 Log your model changes in multiple ways
Stars: ✭ 58 (+262.5%)
Mutual labels:  eloquent, model
Eager Load Pivot Relations
Eager load pivot relations for Laravel Eloquent's BelongsToMany relation.
Stars: ✭ 134 (+737.5%)
Mutual labels:  eloquent, model
Guardian
Eloquent Guardian is a simple permissions system for your users. While there are many other packages for permissions, this one solves everything in the most eloquent way.
Stars: ✭ 121 (+656.25%)
Mutual labels:  eloquent, model
Elasticsearch
The missing elasticsearch ORM for Laravel, Lumen and Native php applications
Stars: ✭ 375 (+2243.75%)
Mutual labels:  eloquent, model
eloquent-filemaker
A Model extension and Eloquent driver for Laravel connecting to FileMaker through the Data API
Stars: ✭ 38 (+137.5%)
Mutual labels:  eloquent, model
Laravel Sluggable
An opinionated package to create slugs for Eloquent models
Stars: ✭ 831 (+5093.75%)
Mutual labels:  eloquent, model
Rating
Laravel Eloquent Rating allows you to assign ratings to any model.
Stars: ✭ 175 (+993.75%)
Mutual labels:  eloquent, model
acorn-db
Provides Acorn projects with Eloquent Models for WordPress data.
Stars: ✭ 30 (+87.5%)
Mutual labels:  eloquent, model
eloquent-hashids
Automatically generate and persist Hashids for newly created Eloquent models.
Stars: ✭ 17 (+6.25%)
Mutual labels:  eloquent
shyft
⬡ Shyft is a server-side framework for building powerful GraphQL APIs 🚀
Stars: ✭ 56 (+250%)
Mutual labels:  model
soft-era-vs-code
🌸 soft era for VS Code ~ Light pastel syntax theme for soft, warm, cozy, cute coding. 🌱
Stars: ✭ 91 (+468.75%)
Mutual labels:  soft
go-topics
Latent Dirichlet Allocation
Stars: ✭ 23 (+43.75%)
Mutual labels:  model
safe-rules
详细的C/C++编程规范指南,由360质量工程部编著,适用于桌面、服务端及嵌入式软件系统。
Stars: ✭ 425 (+2556.25%)
Mutual labels:  safe

Laravel Eloquent Safe Delete


This extension provides "safe" deletion for the Eloquent model, which attempts to invoke force delete, and, if it fails - falls back to soft delete.

For license information check the LICENSE-file.

Latest Stable Version Total Downloads Build Status

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist illuminatech/db-safedelete

or add

"illuminatech/db-safedelete": "*"

to the require section of your composer.json.

Usage

This extension provides "safe" deletion for the Eloquent model, which attempts to invoke force delete, and, if it fails - falls back to soft delete. It works on top of regular Laravel model soft deleting feature.

In case of usage of the relational database, which supports foreign keys, like MySQL, PostgreSQL etc., "soft" deletion is widely used for keeping foreign keys consistence. For example: if user performs a purchase at the online shop, information about this purchase should remain in the system for the future bookkeeping. The DDL for such data structure may look like the following one:

CREATE TABLE `сustomers`
(
   `id` integer NOT NULL AUTO_INCREMENT,
   `name` varchar(64) NOT NULL,
   `address` varchar(64) NOT NULL,
   `phone` varchar(20) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE InnoDB;

CREATE TABLE `purchases`
(
   `id` integer NOT NULL AUTO_INCREMENT,
   `customer_id` integer NOT NULL,
   `item_id` integer NOT NULL,
   `amount` integer NOT NULL,
    PRIMARY KEY (`id`)
    FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE,
    FOREIGN KEY (`item_id`) REFERENCES `items` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE,
) ENGINE InnoDB;

Thus, while set up a foreign key from 'purchase' to 'user', 'ON DELETE RESTRICT' mode is used. So on attempt to delete a user record, which have at least one purchase, a database error will occur. However, if user record have no external reference, it can be deleted.

This extension introduces Illuminatech\DbSafeDelete\SafeDeletes trait, which serves as an enhanced version of standard Illuminate\Database\Eloquent\SoftDeletes, allowing handing foreign key constraints and custom delete allowing logic. Being attached to the model Illuminatech\DbSafeDelete\SafeDeletes changes model's regular delete() method in the way it attempts to invoke force delete, and, if it fails - falls back to soft delete. For example:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminatech\DbSafeDelete\SafeDeletes;

class Customer extends Model
{
    use SafeDeletes;

    public function purchases()
    {
        return $this->hasMany(Purchase::class);
    }

    // ...
}

// if there is a foreign key reference :
$customerWithReference = Customer::query()
    ->whereHas('purchases')
    ->first();

$customerWithReference->delete(); // performs "soft" delete!

// if there is NO foreign key reference :
$customerWithoutReference = Customer::query()
    ->whereDoesntHave('purchases')
    ->first();

$customerWithoutReference->delete(); // performs actual delete!

Heads up! Make sure you do not attach both Illuminate\Database\Eloquent\SoftDeletes and Illuminatech\DbSafeDelete\SafeDeletes in the same model class. It will cause PHP naming conflict error since Illuminate\Database\Eloquent\SoftDeletes is already included into Illuminatech\DbSafeDelete\SafeDeletes.

Smart deletion

Usually "soft" deleting feature is used to prevent the database history loss, ensuring data, which has been in use and perhaps has a references or dependencies, is kept in the system. However, sometimes actual deleting is allowed for such data as well. For example: usually user account records should not be deleted but only marked as "trashed", however if you browse through users list and found accounts, which has been registered long ago, but don't have at least single log-in in the system, these records have no value for the history and can be removed from database to save a disk space.

You can make "soft" deletion to be "smart" and detect, if the record can be removed from the database or only marked as "trashed". This can be done via Illuminatech\DbSafeDelete\SafeDeletes::forceDeleteAllowed(). For example:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminatech\DbSafeDelete\SafeDeletes;

class User extends Model
{
    use SafeDeletes;

    public function forceDeleteAllowed(): bool
    {
        return $this->last_login_at === null;
    }

    // ...
}

$user = User::query()->whereNull('last_login_at')->first();
$user->delete(); // removes the record!!!

$user = User::query()->whereNotNull('last_login_at')->first();
$user->delete(); // marks record as "trashed"

Manual delete flow control

Using Illuminatech\DbSafeDelete\SafeDeletes you can still manually "soft" delete or "force" delete a particular record, using following methods:

  • softDelete() - always performs "soft" deletion.
  • forceDelete() - always performs actual deletion.
  • safeDelete() - attempts to perform actual deletion, if it fails - applies "soft" one.

For example:

<?php

// if there is a foreign key reference :
$customerWithReference = Customer::query()
    ->whereHas('purchases')
    ->first();

$customerWithReference->forceDelete(); // performs actual delete (triggers a database error actually)!

// if there is NO foreign key reference :
$customerWithoutReference = Customer::query()
    ->whereDoesntHave('purchases')
    ->first();

$customerWithoutReference->softDelete(); // performs "soft" delete!

// if there is a foreign key reference :
$customerWithReference = Customer::query()
    ->whereHas('purchases')
    ->first();

$customerWithReference->safeDelete(); // performs "soft" delete!

// if there is NO foreign key reference :
$customerWithoutReference = Customer::query()
    ->whereDoesntHave('purchases')
    ->first();

$customerWithoutReference->safeDelete(); // performs actual delete!
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].