PHP code example of mhdobd / eloquent-relation-guard
1. Go to this page and download the library: Download mhdobd/eloquent-relation-guard library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
mhdobd / eloquent-relation-guard example snippets
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);
}
}
$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
}
$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'=> [],
// ],
// ]
$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.