News

Laravel Deletable Trait

Published
Laravel Deletable Trait image

Laravel Deletable is a package to handle deletion restrictions to your Eloquent models gracefully. The package provides a RestrictsDeletion trait for models you’d like to control deletion:

namespace App;
 
use F9Web\LaravelDeletable\Traits\RestrictsDeletion;
use Illuminate\Database\Eloquent\Model;
 
class User extends Model
{
use RestrictsDeletion;
 
public function isDeletable(): bool
{
return $this->orders->isEmpty();
}
}

When a model’s isDeletable() method returns false, a model exception occurs:

namespace App\Controllers;
 
use F9Web\LaravelDeletable\Exceptions\NoneDeletableModel;
use App\User;
 
class UsersController
{
public function destroy(User $user): bool
{
try {
$user->delete();
} catch (NoneDeletableModel $e) {
dd($e->getMessage());
}
}
}

You can learn more about this package, get full installation instructions, and view the source code on GitHub at f9webltd/laravel-deletable.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Filed in

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Laravel Auditor Audits Your App With Your Own AI Agent image

Laravel Auditor Audits Your App With Your Own AI Agent

Read article
A simple form builder that stays out of your way image

A simple form builder that stays out of your way

Read article
Laravel AI: Trace Agent Runs With Lifecycle Events image

Laravel AI: Trace Agent Runs With Lifecycle Events

Read article
Laravel AI: Get Raw HTTP Responses and Rate Limits image

Laravel AI: Get Raw HTTP Responses and Rate Limits

Read article
Agent Run Observability in Laravel AI SDK 0.11 image

Agent Run Observability in Laravel AI SDK 0.11

Read article
Debounced Queued Event Listeners in Laravel image

Debounced Queued Event Listeners in Laravel

Read article