Table of Contents
Soft deletes in Laravel are a useful feature that lets you remove records from your database without actually deleting them. Instead of permanently deleting a record, soft deletes mark it as “deleted,” which means you can restore the data later on.
This approach offers flexibility, especially when dealing with sensitive information, accidental deletions, or audit requirements. Whether you’re a beginner exploring Laravel’s capabilities or working with experienced Laravel developers, understanding soft deletes can enhance your application’s reliability and data management.
In this blog, we’ll cover the concept of soft deletes in Laravel, how to use them, and some ideal use cases.
What is Soft Delete in Laravel?
Soft deletes in Laravel provide a way to mark records as deleted without actually removing them from the database. Instead of deleting a record permanently, Laravel sets a special column called deleted_at with a timestamp. This column acts as a flag, indicating that the record is deleted. When the value of deleted_at is null, the record is considered active; when it’s populated with a timestamp, it’s marked as deleted.
When queries are run on a table that uses soft deletes, Laravel automatically filters out the records that have a non-null deleted_at value, ensuring that only active records are retrieved by default. This makes soft deletes an efficient way to manage data integrity while still offering flexibility for possible data recovery..
When to Use Soft Deletes:
- User Account Management: If a user deletes their account, soft deletes can retain the data temporarily, allowing restoration if the user changes their mind.
- Data Analytics: Soft deletes can help track trends, usage, or historical data, even if related models are removed.
- Like a Recycle Bin: Laravel soft deletes work as a recycle bin. Just like how files go to the recycle bin on a computer and can be restored or permanently removed later, soft deletes let you manage records similarly.
However, just because soft deletes are enabled doesn’t necessarily mean your application has to offer users the ability to restore or permanently delete the data. The feature might simply be implemented to maintain data history or for internal purposes.
How to Use Soft Deletes in Laravel?
Now that we understand the benefits of soft deletes, let’s dive into the practical steps for implementing them in your Laravel application. This process can be broken down into several key steps:
Step 1: Prepare the Database
The first step in implementing soft deletes involves making adjustments to your database schema. Here’s what you need to do:
1. Add the deleted_at Column. Using a migration, add a new column named deleted_at to the table where you want to enable soft deletes. This column will be of type datetime or timestamp and will store the timestamp of when a record is deleted.
Schema::table('your_table_name', function (Blueprint $table) {
$table->softDeletes();
});
Alternatively, you can manually add the column using a separate migration or SQL query.
2. Laravel Migration Helper. Laravel provides a convenient helper method softDeletes() within your migrations. This method adds the deleted_at column with the appropriate data type and sets it to be nullable.
3. Consider Custom Column Names (Optional). By default, Laravel uses deleted_at for the soft delete column. If you prefer a different name, you can specify it within the softDeletes method call like this:
Schema::table('your_table_name', function (Blueprint $table) {
$table->softDeletes('custom_deleted_at_column_name');
});
Remember to migrate your database schema after making these changes. This will ensure the deleted_at column is added to your table. Once you’ve prepared your database, you’re ready to enable soft deletes within your Laravel models.
Step 2: Enable Soft Deletes in the Model
With the database prepared, it’s time to configure your Laravel models to leverage soft deletes. Here’s how:
1. Include the SoftDeletes Trait. The core functionality for soft deletes resides in Laravel’s SoftDeletes trait. Add this trait to your model class using the use statement at the beginning.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class YourModel extends Model
{
use SoftDeletes;
// ... rest of your model code
}
2. Automatic Management of deleted_at Column. By including the SoftDeletes trait, Laravel handles the deleted_at column. The trait automatically casts the column to a DateTime or Carbon instance. This provides helper methods for working with soft deleted data.
3. No Code Changes Required for Soft Deletion. Including the SoftDeletes trait is all that’s necessary for enabling soft deletes. The trait blocks the default delete() method on your model. Then modifies it to update the deleted_at column with the current timestamp instead of permanently removing the record.
Once you’ve incorporated the SoftDeletes trait, your model is equipped to manage soft deletes in an effective manner. This paves the way for using soft delete functionalities within your Laravel application.
Step 3: Soft Delete a Model
Now that your model is configured for soft deletes, let’s see how to soft delete a model instance. The process is very similar to a traditional delete:
1. Use the delete() Method. The process of soft deleting a model remains very similar to a traditional hard delete. You can use the model instance’s delete() method as usual.
$user = User::find(1);
$user->delete();
2. deleted_at Column Updated. When you call delete() on a model with soft deletes enabled, Laravel will block this action. Instead of permanently removing the record, Laravel will update the deleted_at column with the current timestamp. This marks the record as deleted in a logical way.
3. Model Instance Still Accessible (Optional). Even after soft deletion, the model instance called delete() remains accessible in your code. This can be useful in certain scenarios, such as retrieving information from the model before it’s removed from the database (covered in a later step).
Remember, soft deletion doesn’t physically remove the data from your database. The record is still there but hidden from standard queries. We’ll explore how to retrieve and restore soft deleted data in the following steps.
Step 4: Retrieve Records
By default, Laravel’s Eloquent queries exclude soft-deleted records. This ensures your application primarily works with active data. However, there are scenarios where you might need to retrieve both active and soft-deleted records. Here’s how to achieve that:
1. Retrieve Active Records (Default). Standard Eloquent queries will automatically exclude soft-deleted records. This means you don’t need to make any special modifications to your queries to fetch only active data.
$activeUsers = User::all(); // Retrieves only active users
2. Include Soft-Deleted Records. To retrieve both active and soft-deleted records, you can use the withTrashed() method on your Laravel Eloquent query builder.
$allUsers = User::withTrashed()->get(); // Retrieves all users, including soft-deleted ones
3. Filtering Soft-Deleted Records (Optional). Indeed, withTrashed() retrieves all records. Yet, you can still combine them with other query filters to target specific soft-deleted data.
$softDeletedUsers = User::withTrashed()->where('deleted_at', '>', Carbon::now()->subWeek())->get(); // Retrieves soft-deleted users deleted within the last week
Using these techniques, you can control which records are retrieved by your Laravel queries. With it, you can consider both active and soft-deleted data as needed. We’ll explore how to recover soft-deleted data in the next step.
Step 5: Recover Soft Deleted Records (Optional)
Soft deletes provide a safe space by allowing you to recover accidentally deleted or logically hidden data. Here’s how to restore a soft-deleted record in Laravel:
1. Use the restore() Method. The restore() method on your model instance reinstates a soft-deleted record. This removes the record’s deleted_at timestamp, making it visible and usable again in your application.
$user = User::withTrashed()->find(1);
$user->restore();
2. deleted_at Column Set to Null. When you call restore(), Laravel sets the deleted_at column back to null for the affected record. This removes the soft deletion flag, making the data visible in standard Eloquent queries again.
3. Data Recovery vs Permanent Deletion. It’s important to remember that soft deletes don’t guarantee indefinite data retention. While recovering soft-deleted records is straightforward, you might have separate mechanisms for permanent data deletion.
It’s important to note that this step is optional. Soft-deleted records can remain in your database for any period you deem necessary. We’ll cover permanent deletion as an alternative in the next step.
Step 6: Restore a Soft Deleted Model
Building upon the concept of recovering soft-deleted records, this step focuses on restoring a specific soft-deleted model instance in Laravel.
1. Locate the Soft-Deleted Model. The first step involves identifying the model instance you want to restore. You can use the withTrashed() method on your Eloquent query builder to retrieve soft-deleted records and then filter them based on your criteria (e.g., ID, name, etc.).
$user = User::withTrashed()->find(1);
// Alternatively, filter by other criteria
2. Use the restore() Method. Once you have the soft-deleted model instance, call the restore() method on it. This method removes the deleted_at timestamp associated with the record.
$user->restore();
3. Model Becomes Active Again. After calling restore(), the model is no longer considered logically deleted. The deleted_at column becomes null, and the record is again accessible through standard Eloquent queries. It’s now visible and usable within your application logic.
Remember, restoring a soft-deleted model reverses the soft-deletion process. The data is no longer hidden and can be interacted with like any other active record. We’ll explore the concept of permanent deletion as an optional step in the next section.
Step 7: Permanent Deletion (Optional)
While soft deletes offer a safety net, there might be scenarios where permanent data removal is necessary. Here’s how to permanently delete a model instance in Laravel, even if it’s soft-deleted.
1. Use the forceDelete() Method. Laravel provides the forceDelete() method on your model instance for permanent deletion. This method bypasses the soft delete logic and completely removes the record from the database.
$user = User::withTrashed()->find(1);
$user->forceDelete();
2. Data Recovery Not Possible. Once you call forceDelete(), the record is permanently erased from the database. Unlike soft deletion, there’s no way to recover the data through Laravel’s Eloquent functionalities.
3. Use with Caution. Permanent deletion is an irreversible action. Use forceDelete() precisely, making sure you intend to remove the data permanently. Consider implementing backups or archiving mechanisms for essential data before using this method.
By understanding permanent deletion, you can manage your database storage and ensure compliance with data retention policies. Remember, soft deletes offer a safety net, but permanent deletion provides a way to remove data definitively when necessary.
Struggling with Laravel database management? We can help!
What are Some Other Uses of Soft Deletes in Laravel?
Laravel soft deletes offer a powerful tool for managing data beyond basic deletion functionality. Here are some additional valuable applications of soft deletes in Laravel applications:
1. Audit Trails
Soft deletes can be instrumental in maintaining a log of data changes. By keeping soft-deleted records along with their deleted_at timestamps, you can create a detailed audit trail. This allows you to track who deleted a record when it was deleted, and why it was deleted. It stores a reason alongside the deleted_at timestamp.
2. Temporary Inactivation
Soft deletes are ideal for scenarios where you need to temporarily deactivate user accounts, products, or other data entities. You can remove it from public view or functionality by soft deleting a record. Moreover, you can still preserve the data for potential future reactivation or reference.
3. Data Retention Policies
Soft deletes can help adhere to data retention policies or regulations. By keeping soft-deleted records for a specific period, you can ensure compliance with legal requirements before permanently deleting the data.
4. Shopping Carts and Checkouts
Soft deletes play a vital role in implementing shopping cart functionality. Users can add and remove items from their carts without permanently deleting the data from the database. Soft-deleted cart items can be easily identified and removed during the checkout process.
5. Undo Functionality
Soft deletes can be leveraged to create undo functionality within your application. If a user accidentally deletes data, you can provide an “undo” option that essentially restores the soft-deleted record. This enhances user experience by offering a safety net against accidental data loss.
These are just a few examples of how soft deletes can extend the functionality and flexibility of your Laravel applications. By using soft deletes, you can enhance data management and ensure compliance with various requirements. To unlock the full potential of soft deletes, consider partnering with Laravel development experts. Their expertise can help you design and implement data management tailored to your needs.
FAQs About Soft Deletes in Laravel
Conclusion
Soft deletes in Laravel are a practical way to manage data safely. Instead of removing records completely, they’re marked as deleted using the deleted_at column. This allows you to keep the data for potential recovery or analysis, making your application more flexible.
Whether you’re handling user accounts, tracking data changes, or just need a safety net for accidental deletions, soft deletes can be a useful feature to implement. They’re easy to set up and can help make your data management more reliable.
If you need professional assistance to manage your Laravel database or want to improve your application’s functionality, trust our professional Laravel developers.