Engineering note · Laravel

Keep Data Without Deleting It: Using Laravel Soft Delete

Laravel Soft Delete lets "delete" records without actually removing them from the database. This can be useful when you want to keep data for future recovery.

By Published

Laravel

Step 1: Enable Soft Deletes in Your Model

Add SoftDeletes to your model. Let's take an example with a Post model.

CODE SAMPLE Code snippet
use Illuminate\Database\Eloquent\Model;
// include this line
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;
}

Step 2: Add the Deleted At Column to Your Table

Run a migration to add a deleted_at column(if already not exist). This column keeps track of when a record is "deleted."

CODE SAMPLE Code snippet
php artisan make:migration add_deleted_at_to_posts_table --table=posts

Replace --table=posts with name of your table

In the migration file:

CODE SAMPLE Code snippet
public function up()
{
    Schema::table('posts', function (Blueprint $table) {
        $table->softDeletes();
    });
}

Step 3: Use Soft Delete in Your Application

Now, you can "soft delete" a record:

CODE SAMPLE Code snippet
$post = Post::find(1);
$post->delete(); // Soft delete

Tip: To restore it:

CODE SAMPLE Code snippet
$post->restore(); // Restore the "deleted" post

To get only soft-deleted records:

CODE SAMPLE Code snippet
$trashedPosts = Post::onlyTrashed()->get();

Laravel Soft Delete is an easy way to keep records without permanently deleting them, adding flexibility to your app's data management.

More engineering notes

Implicit and Explicit Route Model Binding

## 1. Implicit Route Model Binding ``` // Define a route with implicit model binding Route::get('us...

Schedule Tasks with Artisan Scheduler

Automate recurring tasks such as sending emails, generating reports, or cleaning up the database usi...