PHPackages                             yousef-aman/prevent-deletion - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Security](/categories/security)
4. /
5. yousef-aman/prevent-deletion

ActiveLibrary[Security](/categories/security)

yousef-aman/prevent-deletion
============================

A package to prevent deletion of models with related records.

v1.0.0(1y ago)114MITPHP

Since May 19Pushed 1y ago1 watchersCompare

[ Source](https://github.com/yousef-aman/prevent-deletion)[ Packagist](https://packagist.org/packages/yousef-aman/prevent-deletion)[ RSS](/packages/yousef-aman-prevent-deletion/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (2)Used By (0)

Prevent Deletion
================

[](#prevent-deletion)

A Laravel package to prevent the deletion of models with related records.

Installation
------------

[](#installation)

### Method 1: Install via Packagist

[](#method-1-install-via-packagist)

1. Run the following command to require the package:

    ```
    composer require yousef-aman/prevent-deletion
    ```

### Method 2: Install via GitHub

[](#method-2-install-via-github)

1. Add the following repository to your `composer.json` file:

    ```
    "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/yousef-aman/prevent-deletion.git"
        }
    ]
    ```
2. Run the following command to require the package:

    ```
    composer require yousef-aman/prevent-deletion
    ```

Usage
-----

[](#usage)

### Step 1: Use the Trait in Your Models

[](#step-1-use-the-trait-in-your-models)

Use the `PreventDeletionIfHasRelations` trait in your models. Define any specific conditions, and optionally, specify which relationships to exclude or include in the check.

#### Example: User Model

[](#example-user-model)

```
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use YousefAman\PreventDeletion\Traits\PreventDeletionIfHasRelations;

class User extends Model
{
    use PreventDeletionIfHasRelations;

    // Exclude 'comments' from the check
    protected $excludedRelations = ['comments'];

    public function blogs()
    {
        return $this->hasMany(Blog::class);
    }

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    public function likes()
    {
        return $this->hasMany(Like::class);
    }

    // Define specific conditions dynamically
    public function specificConditions(): array
    {
        return [
            [
                'condition' => $this->is_active === false,
                'message' => 'Cannot delete this user because it is not active.'
            ],
            [
                'condition' => $this->is_verified === false,
                'message' => 'Cannot delete this user because it is not verified.'
            ]
        ];
    }

    // Optional: Customize deletion message
    public function getDeletionMessage($default)
    {
        return 'Custom deletion message: ' . $default;
    }
}
```

#### Example: Blog Model

[](#example-blog-model)

```
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use YousefAman\PreventDeletion\Traits\PreventDeletionIfHasRelations;

class Blog extends Model
{
    use PreventDeletionIfHasRelations;

    // No exclusions in this example
    protected $excludedRelations = [];

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // Define specific conditions dynamically
    public function specificConditions(): array
    {
        return [
            [
                'condition' => $this->is_published === false,
                'message' => 'Cannot delete this blog because it is not published.'
            ]
        ];
    }

    // Optional: Customize deletion message
    public function getDeletionMessage($default)
    {
        return 'Custom deletion message: ' . $default;
    }
}
```

### Step 2: Handle Deletion in Controllers

[](#step-2-handle-deletion-in-controllers)

Handle the exception in your controller to provide a user-friendly message:

```
namespace App\Http\Controllers;

use App\Models\User;
use YousefAman\PreventDeletion\Exceptions\PreventDeletionException;
use Exception;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function destroy($id)
    {
        try {
            $user = User::findOrFail($id);
            $user->delete();
            return redirect()->back()->with('success', 'User deleted successfully.');
        } catch (PreventDeletionException $e) {
            // Handle deletion prevention specifically
            return redirect()->back()->with('error', $e->getMessage());
        } catch (Exception $e) {
            // Handle other exceptions
            return redirect()->back()->with('error', 'An error occurred: ' . $e->getMessage());
        }
    }
}
```

Features
--------

[](#features)

### 1. Custom Exception Handling

[](#1-custom-exception-handling)

The package uses a custom `PreventDeletionException` class to handle exceptions specifically related to deletion prevention. This makes it easier to catch and handle these exceptions separately from other types of exceptions.

```
namespace YousefAman\PreventDeletion\Exceptions;

use Exception;

class PreventDeletionException extends Exception
{
    /**
     * Create a new PreventDeletionException instance.
     *
     * @param  string  $message
     * @param  int  $code
     * @param  \Exception|null  $previous
     * @return void
     */
    public function __construct($message = "", $code = 0, Exception $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }
}
```

### 2. Logging

[](#2-logging)

The package integrates logging to record attempts to delete models with related records. This helps in debugging and monitoring.

### 3. Configurable Messages

[](#3-configurable-messages)

Models can define custom messages for deletion prevention scenarios, making the package more flexible.

```
public function getDeletionMessage($default)
{
    return $this->deletionMessage ?? $default;
}
```

### 4. Extending Configuration

[](#4-extending-configuration)

The package allows for detailed control over which relations are checked by specifying `excludedRelations` and `includedRelations`.

Contributing
------------

[](#contributing)

Thank you for considering contributing to this package! You can contribute by opening an issue or submitting a pull request.

License
-------

[](#license)

This package is open-source software licensed under the [MIT license](https://opensource.org/licenses/MIT).

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance31

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

723d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/63d653ed6370600b708eb55f0ee855213af337b541af12308068dde21ec658a9?d=identicon)[yousef-aman](/maintainers/yousef-aman)

---

Top Contributors

[![yousef-aman](https://avatars.githubusercontent.com/u/59014877?v=4)](https://github.com/yousef-aman "yousef-aman (2 commits)")

### Embed Badge

![Health badge](/badges/yousef-aman-prevent-deletion/health.svg)

```
[![Health](https://phpackages.com/badges/yousef-aman-prevent-deletion/health.svg)](https://phpackages.com/packages/yousef-aman-prevent-deletion)
```

###  Alternatives

[defuse/php-encryption

Secure PHP Encryption Library

3.9k162.4M214](/packages/defuse-php-encryption)[roave/security-advisories

Prevents installation of composer packages with known security vulnerabilities: no API, simply require it

2.9k97.3M6.4k](/packages/roave-security-advisories)[mews/purifier

Laravel 5/6/7/8/9/10 HtmlPurifier Package

2.0k16.7M113](/packages/mews-purifier)[robrichards/xmlseclibs

A PHP library for XML Security

41278.1M118](/packages/robrichards-xmlseclibs)[bjeavons/zxcvbn-php

Realistic password strength estimation PHP library based on Zxcvbn JS

86917.5M63](/packages/bjeavons-zxcvbn-php)[enlightn/security-checker

A PHP dependency vulnerabilities scanner based on the Security Advisories Database.

33732.2M110](/packages/enlightn-security-checker)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
