Soft Deletes in Laravel: An Introduction
What are Soft Deletes?
In the context of Laravel's Eloquent ORM, soft deleting a model means the record isn't removed from the database. Instead, a deleted_at
timestamp is set for that record. By default, models that have been soft deleted will be excluded from query results.
Setting up Soft Deletes
To utilize the soft deletes functionality, some setup is required:
1. Database Migration:
Your model's corresponding database table requires a deleted_at
column. You can add this using a migration:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class UpdateBooksTableForSoftDeletes extends Migration
{
public function up()
{
Schema::table('books', function(Blueprint $table){
$table->softDeletes(); //this will add a deleted_at column
});
}
public function down()
{
Schema::table('books',function(Blueprint $table){
$table->dropSoftDeletes(); // This removes the deleted_at column
});
}
}
After creating the migration, execute it with:
php artisan migrate
2. Update the Model:
The Eloquent model needs to use the SoftDeletes
trait. This trait overrides the model's default delete()
behavior to implement soft deleting and provides additional methods to interact with soft deleted records.
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Book extends Model
{
use SoftDeletes;
// ... rest of the model code ...
}
The inclusion of the SoftDeletes
trait is crucial. It ensures that calling delete()
on a model instance won't remove it from the database but will set its deleted_at
timestamp, marking it as 'deleted'.
Soft Deleting in Action:
To soft delete a model instance:
$book = App\Book::find(1); // Find a book by ID
$book->delete(); // This will soft delete the book
Interacting with Soft Deleted Models:
- Fetching Including Soft Deleted Models:
$books = App\Book::withTrashed()->get();
- Fetching Only Soft Deleted Models:
$deletedBooks = App\Book::onlyTrashed()->get();
- Restoring Soft Deleted Models:
$book = App\Book::onlyTrashed()->where('id', 1)->first();
$book->restore();
Conclusion:
Soft deletes provide an elegant way to manage deletions in Laravel applications without permanent data loss. It's essential for scenarios where data recovery is critical or where the 'deletion' is more of a state than a data removal action. Always ensure you understand the underlying mechanism and the implications of using soft deletes in your application.