PHPackages                             mhdobd/eloquent-relation-guard - 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. [Database &amp; ORM](/categories/database)
4. /
5. mhdobd/eloquent-relation-guard

ActiveLibrary[Database &amp; ORM](/categories/database)

mhdobd/eloquent-relation-guard
==============================

A Laravel package for scanning model relations, And providing useful actions over them

v0.9.0(11mo ago)14MITPHPPHP &gt;=8.0

Since Jun 3Pushed 11mo ago1 watchersCompare

[ Source](https://github.com/MuhammadObadaa/eloquent-relation-guard)[ Packagist](https://packagist.org/packages/mhdobd/eloquent-relation-guard)[ RSS](/packages/mhdobd-eloquent-relation-guard/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (1)Versions (2)Used By (0)

[![Package logo](/art/logo.jpg)](/art/logo.jpg)

Eloquent Relation Guard
=======================

[](#eloquent-relation-guard)

Laravel package by [MuhammadObadaa](https://github.com/MuhammadObadaa)

---

**Scan, inspect, and (optionally) force‐delete Eloquent models along with their HasOne/HasMany branches—without relying on database‐level cascade or restrict rules.**

> OnDelete, you can walk through a model’s HasOne/HasMany relations (to any depth), get a nested “tree” of related IDs, check whether a model is safe to delete, or forcibly delete the entire sub‐tree in one shot.

---

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

[](#installation)

Require the package via Composer:

```
composer require mhdobd/eloquent-relation-guard
```

---

Configuration
-------------

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --provider="EloquentRelation\Guard\EloquentRelationGuardServiceProvider" --tag="config"
```

This will copy `config/eloquent-relation-guard.php` into your application’s `config/` directory.

---

Usage
-----

[](#usage)

1. **Use the Trait in Your Model**Add the `HasRelationalDependencies` trait to any Eloquent model you want to protect/scan.

    ```
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\Relations\HasMany;
    use EloquentRelation\Guard\Traits\HasRelationalDependencies;

    class Post extends Model
    {
        use HasRelationalDependencies;

        /**
         * By default, all HasOne/HasMany relations will be scanned.
         * If you want to limit or specify nested branches, define:
         */
        protected array $scanRelations = [
            'comments',             // only scan Post::comments()
            'comments.replies',     // also scan replies under each comment
            'tags',                 // scan Post::tags() (if tags is a HasMany relationship)
            '*'                     // or simply, add all first-level relations
        ];

        // Type hint (mention the return type of) each HasOne/HasMany relation method
        public function comments(): HasMany
        {
           return $this->hasMany(Comment::class);
        }
    }
    ```
2. **Check if a Record Can Be Deleted**

    ```
    $post = Post::find(42);

    if ($post->canBeSafelyDeleted()) {
        // no related HasOne/HasMany records exist
        $post->delete();
    } else {
        // there are related records—perhaps alert the user
        // so you can alert the user with detailed related relations using $post->relationStructure
    }
    ```
3. **Get the Full Relation “Tree” (with IDs)**

    ```
    $post = Post::find(42);

    // Pass a depth (integer) to limit how many levels deep to scan.
    // Use -1 for no depth limit, only memory and time one.
    $tree = $post->relationStructure(depth:2);
    // $tree will look like:
    // [
    //   'comments' => [
    //       'ids'   => [10, 11, 12],
    //       'model' => 'App\Models\Comment',
    //       'nested'=> [
    //           'replies' => [
    //               'ids'   => [101, 102],
    //               'model' => 'App\Models\CommentReply',
    //               'nested'=> [ /* … */ ],
    //           ],
    //       ],
    //   ],
    //   'tags' => [
    //       'ids'   => [5, 6],
    //       'model' => 'App\Models\Tag',
    //       'nested'=> [],
    //   ],
    // ]
    ```
4. **Force‐Delete a Model and All Related Records**

    ```
    $post = Post::find(42);
    $deletedCount = $post->forceCascadeDelete();
    // This will delete all HasOne/HasMany descendants (ignoring DB foreign‐key rules)
    // and then delete the Post itself. $deletedCount is the total number of records removed.
    ```
5. **Console Command: `record:tree`**You can visualize a model’s relation tree (with IDs) from the CLI:

    ```
    php artisan record:tree Post 42 2
    ```

    - `Post` : The model class name, it should be located in `app/models/` directory
    - `42` : ID of the record to inspect
    - `2` : Depth (how many nested levels to scan; use `-- -1` for unlimited)

    **Example Output:**

    ```
    Relation Tree for App\Models\Post (ID: 42) | Depth: 2
    ├── comments (App\Models\Comment): [10, 11, 12]
    │   └── replies (App\Models\CommentReply): [101, 102]
    └── tags (App\Models\Tag): [5, 6]

    ```

for more details check the [Documentation](Documentation.md)

---

TODO
----

[](#todo)

- Add support for **soft deletes** (detecting `deleted_at` and deciding whether to include or ignore soft‐deleted records).
- Support **morph relations** along with HasOne and HasMany relations.
- Allow **configurable thresholds** for maximum nodes/depth before aborting the scan.
- Add **event hooks** (e.g., `beforeDeleteGuarded`, `afterDeleteGuarded`) so users can tap into the delete process.
- Provide **Laravel Nova/Filament** integrations for visual “Are you sure?” modals.
- Mark visited classes when **DFS over them** so it can avoid cyclic database relations.
- Write **feature tests** and include sample migrations/seeders.
- Add **Complexity Details** in documentation file.
- Optimize **Time, Memory, and DB Query** complexity over core package logic implementation.

---

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

[](#contributing)

If you discover bugs, have feature requests, or want to contribute code, please use the GitHub issue tracker:

> **Issues &amp; Contributions**:

Feel free to fork the repository, open a PR, and follow these basic guidelines:

1. Fork the repo and create a new branch for your feature/fix.
2. Write at least one test (where applicable) demonstrating the expected behavior.
3. Update `CHANGELOG.md` and `README.md` if you add or change functionality.
4. Submit a pull request—describe what you changed and why.

---

License
-------

[](#license)

**Eloquent Relation Guard** package is open source, licensed under [MIT](LICENSE). Feel free to use, modify, and redistribute.

###  Health Score

25

—

LowBetter than 37% of packages

Maintenance51

Moderate activity, may be stable

Popularity5

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity31

Early-stage or recently created project

 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

341d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/34b149df26748455cd289266b9dd88db35d9dee2d9d2ad5b8a3ba02c59e0ac6b?d=identicon)[MuhammadObadaa](/maintainers/MuhammadObadaa)

---

Top Contributors

[![MuhammadObadaa](https://avatars.githubusercontent.com/u/99404326?v=4)](https://github.com/MuhammadObadaa "MuhammadObadaa (6 commits)")

---

Tags

laravellaravel-eloquentlaravel-packagemodelpackagemodeleloquentrelationshasOnehasmanyforceCascadeDelete

### Embed Badge

![Health badge](/badges/mhdobd-eloquent-relation-guard/health.svg)

```
[![Health](https://phpackages.com/badges/mhdobd-eloquent-relation-guard/health.svg)](https://phpackages.com/packages/mhdobd-eloquent-relation-guard)
```

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[spiritix/lada-cache

A Redis based, automated and scalable database caching layer for Laravel

591444.8k2](/packages/spiritix-lada-cache)[pdphilip/elasticsearch

An Elasticsearch implementation of Laravel's Eloquent ORM

145360.2k4](/packages/pdphilip-elasticsearch)[highsolutions/eloquent-sequence

A Laravel package for easy creation and management sequence support for Eloquent models with elastic configuration.

121130.3k](/packages/highsolutions-eloquent-sequence)

PHPackages © 2026

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