PHP

Implementing Soft Deletes and Restoration in Laravel Eloquent

Utilize Laravel Eloquent's soft deletes feature to gracefully manage deleted records, allowing for easy restoration and preventing permanent data loss in your application.

// app/Models/Post.php
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;
    // ... other model properties and methods
}

// In your controller or other logic:

// Soft delete a post
$post = Post::find(1);
$post->delete(); // This sets the 'deleted_at' timestamp

// Retrieve only soft deleted posts
$trashedPosts = Post::onlyTrashed()->get();

// Retrieve all posts, including soft deleted ones
$allPosts = Post::withTrashed()->get();

// Restore a soft deleted post
$trashedPost = Post::onlyTrashed()->find(1);
if ($trashedPost) {
    $trashedPost->restore(); // This sets 'deleted_at' to null
}

// Permanently delete a soft deleted post
$trashedPost->forceDelete();
How it works: Soft deletes in Laravel Eloquent prevent actual deletion of records from your database. Instead, a `deleted_at` timestamp is set on the record. This allows you to easily retrieve, restore, or even permanently delete records later. To enable soft deletes, add the `SoftDeletes` trait to your model and ensure your database table has a `deleted_at` timestamp column. Eloquent provides convenient methods like `onlyTrashed()`, `withTrashed()`, `restore()`, and `forceDelete()` for managing these records.

Need help integrating this into your project?

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

Hire DigitalCodeLabs