020 8090 9664
Map
  • Support
    • Raise a ticket
    • Call support
    • Network status
    • Support Hub
  • Login
    • Platform
  • HOW TO RAISE A SUPPORT TICKET
  • 020 8090 9664
  • Raise a Ticket
    Call Support
    Network Status
    Knowledge Base

    Nimbus
    • Managed Hosting
      • Hosting for WordPress
      • Magento
      • PHP Applications
      • Laravel Hosting
      • Ecommerce
      • Reseller Hosting
    • Servers
      • Server Hosting
      • VPS Servers
    • Platform
      • Agency Hosting Platform
      • NimCache Ultra
      • NimShield
      • NimWatch
    • Pricing
    • Sectors
      • I'm an agency
      • I'm a developer
      • I'm a freelancer
    • Resources
      • Blog
      • E-books
      • Reports
      • Webinars
      • Case Studies
    • Contact
  • Managed Hosting
    • Hosting for WordPress
    • Magento
    • PHP Applications
    • Laravel Hosting
    • Ecommerce
    • Reseller Hosting
  • Servers
    • Server Hosting
    • VPS Servers
  • Platform
    • Agency Hosting Platform
    • NimCache Ultra
    • NimShield
    • NimWatch
  • Pricing
  • Sectors
    • I'm an agency
    • I'm a developer
    • I'm a freelancer
  • Resources
    • Blog
    • E-books
    • Reports
    • Webinars
    • Case Studies
  • Contact
  • Home Blog Laravel Soft Deletes: A Comprehensive Guide
    Laravel Soft Deletes: A Comprehensive Guide
    Share article on Twitter
    Share article on LinkedIn
    Share article on Facebook

    Laravel Soft Deletes: A Comprehensive Guide

    By John | 11 Oct 24

    1. What is Laravel Migration Soft Delete?
    2. How to Use Soft Deletes in Laravel
    3. Configuring Soft Deletes in Migrations
    4. Enabling Soft Deletes in Models
    5. Need Laravel Hosting?
    6. Querying Soft Deleted Records
    7. Restoring Soft Deleted Records
    8. Soft Delete Event Handlers
    9. Best Practices and Tips For Using Soft Deletes in Laravel
    10. Meeting Regulatory Requirements With Soft Delete
    11. Conclusion
    • What is Laravel Migration Soft Delete?
    • How to Use Soft Deletes in Laravel
    • Configuring Soft Deletes in Migrations
    • Enabling Soft Deletes in Models
    • Need Laravel Hosting?
    • Querying Soft Deleted Records
    • Restoring Soft Deleted Records
    • Soft Delete Event Handlers
    • Best Practices and Tips For Using Soft Deletes in Laravel
    • Meeting Regulatory Requirements With Soft Delete
    • Conclusion

    Laravel Soft Deletes allows you to mark records as “deleted” without actually removing them from the database. Instead of permanently deleting a record, Laravel sets a `deleted_at` timestamp, indicating the record is “soft deleted” but still present in the database. This provides a safeguard against accidental data loss and allows you to recover accidentally deleted data when you need to.

     

    This guide will cover the entire process of setting up and using Soft Deletes in Laravel, from configuring migrations to querying soft-deleted records – so, let’s get started, shall we?

    What is Laravel Migration Soft Delete?

    Soft delete is a technique where instead of removing a record from the database, a `deleted_at` column is populated with a timestamp. This tells Laravel that the record is “deleted” without actually removing it from the database.

     

    When querying the database, Laravel automatically excludes records where the `deleted_at` column is not `null`. With soft deletes enabled, it means you can easily recover “deleted” data (because it’s not actually deleted) and carry out auditing changes.

    How to Use Soft Deletes in Laravel

    Configuring Soft Deletes in Migrations

    To enable soft deletes for a table, you need to modify the migration file for the table you want to apply this feature to. Laravel provides a built-in method `softDeletes()` that adds the `deleted_at` column to your database’s existing table.

     

    Example Migration:

     

    use Illuminate\Database\Migrations\Migration;

    use Illuminate\Database\Schema\Blueprint;

    use Illuminate\Support\Facades\Schema;

    class AddSoftDeletesToPostsTable extends Migration

    {

    /**

    * Run the migrations.

    *

    * @return void

    */

    public function up()

    {

    Schema::table(‘posts’, function (Blueprint $table) {

    $table->softDeletes(); // Adds the deleted_at column

    });

    }

    /**

    * Reverse the migrations.

    *

    * @return void

    */

    public function down()

    {

    Schema::table(‘posts’, function (Blueprint $table) {

    $table->dropSoftDeletes(); // Removes the deleted_at column

    });

    }

    }

     

    • `softDeletes()`– This method adds a nullable `deleted_at` timestamp column to your table.
    • `dropSoftDeletes()`– This method is used to drop the `deleted_at` column in case you roll back the migration.

     

    After adding this to your migration files, run:

     

    php artisan migrate

    Enabling Soft Deletes in Models

    After adding the `softDeletes()` column in your migration, and before you start testing soft deletes, you need to tell the Eloquent model to use your new Soft Deletes, otherwise, they will be ignored. This can be done by including the `SoftDeletes` trait in your model.

     

    Example Model:

     

    namespace App\Models;

    use Illuminate\Database\Eloquent\Model;

    use Illuminate\Database\Eloquent\SoftDeletes;

    class Post extends Model

    {

    use SoftDeletes;

    protected $dates = [‘deleted_at’]; // Optional but recommended if you’re working with date casting

    }

     

    • `use SoftDeletes;`– This trait activates the Soft Delete functionality for the model.
    • `$dates`– This optional property ensures the `deleted_at` field is treated as a `Carbon` instance (for date handling) instead of a plain string.

    Need Laravel Hosting?

    Choose Nimbus for your Laravel hosting and enjoy lightning-fast, secure and private servers that can handle all of your websites and apps and not get bogged down!

    Querying Soft Deleted Records

    By default, when soft-deleted models are enabled, Eloquent will exclude soft-deleted records from all queries. If this type of data deletion is your desired outcome, it’s time to grab a coffee and admire your work. If you’d like to include certain soft deleted records in your queries, here’s how you do it:

     

    Retrieving Soft Deleted Records

     

    To include soft-deleted records in your queries, you can use the `withTrashed()` method.

    // Retrieve all records, including soft-deleted ones

    $posts = Post::withTrashed()->get();

     

    Retrieving Only Trashed (Soft Deleted) Records

     

    To only retrieve soft-deleted (trashed) records, use the `onlyTrashed()` method.

    // Retrieve only soft-deleted records

    $trashedPosts = Post::onlyTrashed()->get();

    Restoring Soft Deleted Records

    To restore a soft-deleted record, use the `restore()` method on the Eloquent model. This sets the `deleted_at` column back to `null`, effectively “undeleting” the record.

    Restoring a single record:

     

    $post = Post::withTrashed()->find(1);

    $post->restore();

    Restoring multiple records:

     

    Post::withTrashed()->where(‘author_id’, 1)->restore();

     

    Permanently Deleting Soft Deleted Records

     

    If you need to permanently delete a record (i.e., remove it from the database), use the `forceDelete()` method.

    // Permanently delete a soft-deleted record

    $post = Post::withTrashed()->find(1);

    $post->forceDelete();

     

    Permanently deleting multiple records:

     

    Post::onlyTrashed()->forceDelete();

    Soft Delete Event Handlers

    Laravel provides events for Soft Deletes that you can hook into by adding observers. These events can be useful for logging or notifying when a record is soft-deleted or restored.

     

    The key events related to soft deletes include:

     

    `softDeleted`– Triggered when a model is soft-deleted.

    `restored`– Triggered when a soft-deleted model is restored.

     

    To create an observer for these events:

    class PostObserver

    {

    public function softDeleted(Post $post)

    {

    // Logic for when the post is soft deleted

    }

    public function restored(Post $post)

    {

    // Logic for when the post is restored

    }

    }

    // Register the observer in your service provider

    Post::observe(PostObserver::class);

    Best Practices and Tips For Using Soft Deletes in Laravel

    Use Soft Deletes for Recoverability – If you expect to recover data in the future (e.g., users, posts, orders), soft deletes provide a safer deletion strategy. It ensures that you have access to customer data, accidentally deleted content and more easily. Not to mention, soft delete functionality ensures that you have database tables for audit trails for legal or compliance reasons.

     

    Always Use `forceDelete()` Cautiously – Ensure you only use `forceDelete()` when you’re certain the data should be deleted permanently. Once you ‘forceDelete'() something, not even soft delete can save you!

     

    Batch Soft Deletes – For performance reasons, consider batch-processing soft deletes when dealing with large datasets. For example, using `onlyTrashed()->chunk()` for large record sets. This will keep websites and apps running quickly and your data safe.

     

    Regularly Clean Up Old Soft-Deleted Records – If you have records that are no longer needed after a certain period, you can create a scheduled task to permanently delete soft-deleted records after a certain period.

     

    Example:

    Post::onlyTrashed()->where(‘deleted_at’, ‘<‘, now()->subMonths(6))->forceDelete();

    Double-check and triple-check before deleting data, though.

    Meeting Regulatory Requirements With Soft Delete

    Soft delete is a great way of removing data from your system to keep it running fast and smoothly while keeping the data stored safely. However, you still need to meet regulatory requirements and soft-deleted records often don’t meet these requirements.

     

    Let’s take GDPR as an example. In the case of GDPR, data must be completely removed if it’s required by the user. To comply with this, you’ll need to run a purge process in addition to soft delete. This purge process can affect related business data, so you’ll need to be careful not to delete data you can’t afford to lose!

    Conclusion

    Laravel Soft Deletes offer a powerful way to manage deletions without permanently removing data. They can help you speed up your apps and websites without losing important data. By using the `SoftDeletes` trait, modifying your migrations, and understanding the querying mechanisms, you can take full advantage of this feature to ensure your application can handle deletions gracefully while maintaining data integrity.

    John Headshot

    POSTED BY John

    I'm John, and I work in the dev team. We bring you the coolest time-saving features in our awesome hosting app.

    3 quick facts:
    Expert Lego builder 👷‍♂️ Reasonable guitar player 🎸 Avid watcher of Peppa Pig 🐷

    John Headshot

    POSTED BY John

    I'm John, and I work in the dev team. We bring you the coolest time-saving features in our awesome hosting app.

    3 quick facts:
    Expert Lego builder 👷‍♂️ Reasonable guitar player 🎸 Avid watcher of Peppa Pig 🐷

    Nimbus

    The hosting platform for ambitious UK agencies and freelancers

    Facebook Instagram Twitter LinkedIn YouTube

    Products

    • Hosting
    • Platform
    • Dedicated Servers
    • Pricing

    Resources

    • Blog
    • Support Hub
    • Network Status
    • Raise a Ticket
    • Support

    Terms & Conditions

    • Cancellations & Downgrades
    • Complaints Advice
    • Cookie Policy
    • Customer Privacy Notice
    • Information Security Policy
    • Payment & Delivery Policy
    • Privacy Policy
    • Terms & Conditions

    Company

    • Team
    • Careers
    • Reviews
    • Contact
    • Ecommerce

    © 2025 Nimbus Hosting Ltd. All rights reserved. Registered in England, Company No. 07366355