How to use soft-delete models in Laravel 10 with Examples?
In Laravel, soft-deletes provide a convenient way to mark records as deleted without actually removing them from the database.
This feature is particularly useful when dealing with data that may need to be restored or used for historical purposes.
With Laravel 10, the soft-delete functionality has been further improved, providing developers with even more flexibility and control.
In this article, we will explore what soft-deletes are in Laravel, why we need them, and how to implement them in a practical example project.
What is Soft-Delete in Laravel?
Soft-deletes in Laravel allow you to mark records as “deleted” without permanently removing them from the database. When a record is soft-deleted, Laravel sets a timestamp in a dedicated column, typically named deleted_at, indicating the time of deletion.
The soft-delete feature in Laravel is achieved by utilizing the SoftDeletes trait provided by the framework. This trait adds the necessary functionality to handle soft-deletes automatically.
Why Do We Need Soft-Deletes?
Soft-deletes offer several advantages over hard-deletes, where records are permanently removed from the database. Here are some of the reasons why soft-deletes are beneficial:
1. Data Recovery and Auditing
By utilizing soft-deletes, you retain the ability to recover deleted data if needed. By removing the deleted_at
timestamp, you can easily restore soft-deleted records, enabling a more flexible data recovery process. Additionally, soft-deletes enable you to maintain a historical record of data changes, which can be valuable for auditing purposes.
2. Data Integrity
Soft-deletes ensure that relationships between models remain intact. When deleting a parent model, the system will automatically soft-delete all the child models. With hard-deletes, you would need to manually handle the deletion of related records, which can be error-prone and time-consuming.
3. User Experience
Soft-deletes offer a better user experience by allowing users to recover accidentally deleted data. It provides an extra layer of protection, reducing the risk of data loss due to accidental deletions. Users can easily undo a soft-delete operation without having to rely on database backups or other complex recovery processes.
Example Project: Implementing Soft-Deletes in Laravel 10
To demonstrate the use case of soft-deletes in Laravel 10, let’s consider a simple example project involving a blog application with Post and Comment models. We will enable soft-deletes on both models and explore how they can be utilized.
Create a New Laravel Project
Start by creating a new Laravel project using the Laravel installer or Composer:
bash
laravel new blog-app
Generate the Models and Migrations
Generate the Post and Comment models and their respective migrations using Artisan’s make:model
and make:migration
commands:
php artisan make:model Post -m php artisan make:model Comment -m
Update the Migrations
Open the generated migration files for both Post and Comment models and add the necessary columns. In this case, we need to include the deleted_at
column for soft-deletes. Update the migration files as follows:
Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('content'); $table->softDeletes(); $table->timestamps(); }); Schema::create('comments', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('post_id'); $table->text('content'); $table->softDeletes(); $table->timestamps(); $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); });
Update the Models
Open the Post and Comment models and import the SoftDeletes
trait from Laravel. Additionally, make sure to include the $dates
property to treat the deleted_at
column as a DateTime
instance. Update the models as follows:
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Post extends Model { use SoftDeletes; protected $dates = ['deleted_at']; } use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Comment extends Model { use SoftDeletes; protected $dates = ['deleted_at']; }
Migrate the Database
Run the database migrations to create the necessary tables:
php artisan migrate
Testing Soft-Deletes
Now, let’s test the soft-deletes functionality. In your desired route or controller method, you can use the following code to create, retrieve, soft-delete, and restore posts and comments:
$post = Post::create([ 'title' => 'Example Post', 'content' => 'Lorem ipsum dolor sit amet.', ]); $comment = Comment::create([ 'post_id' => $post->id, 'content' => 'This is a comment.', ]); $post->delete(); $posts = Post::all(); $comments = Comment::withTrashed()->get(); $post->restore();
With this code, you can create a post, associate a comment with it, soft-delete the post, retrieve all posts (excluding soft-deleted ones), retrieve all comments (including soft-deleted ones), and restore the soft-deleted post.
Conclusion
By following the example project outlined in this guide, you can get hands-on experience with soft-deletes in Laravel 10 and incorporate this feature into your own projects. So go ahead, start leveraging soft-deletes and unlock the benefits of non-destructive data management in your Laravel applications!