PHP

Implement Soft Deletes for Non-Destructive Data Removal in Eloquent

Utilize Laravel Eloquent's soft deletes feature to gracefully mark records as deleted without actually removing them from the database, allowing for easy restoration.

// In App\Models\Post.php
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;

    // ... other model properties
}

// To delete a record (soft delete)
$post = App\Models\Post::find(1);
$post->delete(); // 'deleted_at' column is updated

// To retrieve only non-deleted records (default behavior)
$activePosts = App\Models\Post::all();

// To retrieve all records, including soft-deleted ones
$allPosts = App\Models\Post::withTrashed()->get();

// To retrieve only soft-deleted records
$deletedPosts = App\Models\Post::onlyTrashed()->get();

// To restore a soft-deleted record
$post = App\Models\Post::withTrashed()->find(1);
$post->restore();

// To permanently delete a record
$post = App\Models\Post::find(1);
$post->forceDelete();
How it works: Soft deletes provide a way to 'delete' records without actually removing them from your database. Instead, a `deleted_at` timestamp column is set on the model. This allows for easy restoration of records and maintains data integrity. Eloquent queries will automatically exclude soft-deleted records unless `withTrashed()` or `onlyTrashed()` is explicitly used to include or filter for them.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs