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.
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.
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:
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.
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.
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.
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.
Start by creating a new Laravel project using the Laravel installer or Composer:
bash
laravel new blog-app
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
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:
// database/migrations/2023_07_02_create_posts_table.php Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('content'); $table->softDeletes(); // Add this line $table->timestamps(); }); // database/migrations/2023_07_02_create_comments_table.php Schema::create('comments', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('post_id'); $table->text('content'); $table->softDeletes(); // Add this line $table->timestamps(); $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); });
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:
// app/Models/Post.php use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Post extends Model { use SoftDeletes; protected $dates = ['deleted_at']; // Rest of the model code... } // app/Models/Comment.php use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Comment extends Model { use SoftDeletes; protected $dates = ['deleted_at']; // Rest of the model code... }
Run the database migrations to create the necessary tables:
php artisan migrate
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:
// routes/web.php or your controller method // Create a new post $post = Post::create([ 'title' => 'Example Post', 'content' => 'Lorem ipsum dolor sit amet.', ]); // Create a new comment for the post $comment = Comment::create([ 'post_id' => $post->id, 'content' => 'This is a comment.', ]); // Soft-delete the post $post->delete(); // Retrieve all posts (excluding soft-deleted) $posts = Post::all(); // Retrieve all comments (including soft-deleted) $comments = Comment::withTrashed()->get(); // Restore the soft-deleted post $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.
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!
Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…
Let's understand about how to use coding to improve your website's SEO. In today’s computerized…
Let's understand the most important linux commands for web developers. Linux, as an open-source and…
Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…
Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…
Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…