Have you ever wanted to delete data in your Laravel 10 application without actually removing it permanently? Soft Delete is the answer! In this guide, we'll show you step by step how to add Soft Delete to your Laravel 10 project.
With Soft Delete, you can 'softly' remove items from your database while still having the option to bring them back when needed.
Let's learn how to do it!
Here's a step-by-step guide on how to add Soft Delete functionality in a Laravel 10 application:
If you haven't already, set up a new Laravel 10 project by running the following command in your terminal:
composer create-project laravel/laravel my-laravel-project
In your Laravel project, open the .env
file, and make sure you have a valid database connection configured.
Create a new model with Artisan. For example, let's create a "Post" model:
php artisan make:model Post
In the generated Post.php
model file, add the use SoftDeletes
statement at the top, and also include the softDeletes
trait in the class definition:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
}
This will enable Soft Delete for your "Post" model.
Generate a migration for the table you want to add Soft Delete to. In this example, we'll use "posts" as the table name:
php artisan make:migration add_deleted_at_to_posts_table --table=posts
This command generates a migration file. Open the migration file (located in the database/migrations
directory) and add a softDeletes
column to your table.
Here's an example:
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->softDeletes();
});
}
Execute the migration to apply the Soft Delete changes to your database:
php artisan migrate
In your controller that manages the model (e.g., PostController.php
), make sure you use the Post
model and modify your code to work with Soft Deletes. For example, you can use the withTrashed
method to retrieve deleted records as well:
use App\Models\Post;
public function index()
{
// Retrieve all posts (including soft-deleted)
$posts = Post::withTrashed()->get();
// Your logic here
}
You can soft delete a record like this:
$post = Post::find($id);
$post->delete();
To restore a soft-deleted record, you can use the restore
method:
$post = Post::withTrashed()->find($id);
$post->restore();
That's it! You've successfully added Soft Delete functionality to your Laravel 8/9/10 project, allowing you to safely delete and recover records as needed.
You might also like:
- Read Also: How To Export CSV File In Laravel 10 Example
- Read Also: How to Delete Relationship Records in Laravel 10
- Read Also: Laravel 10 AJAX CRUD Operations With Popup Modal
- Read Also: How to Create Multiple Database Connections in Laravel 10