Bookmark

Soft Deletes Made Simple: Laravel 11 Essentials for Developers

Soft Deletes Made Simple: Laravel 11 Essentials for Developers

Soft deletes are a powerful feature in Laravel that allow developers to retain records in the database even after they are marked as deleted. Instead of permanently removing records, soft deletes use a timestamp to indicate when a record was deleted, enabling developers to restore or permanently delete these records later. Laravel 11 builds upon this functionality with refined capabilities to enhance application robustness and user experience.

Setting Up Soft Deletes

Add the `deleted_at` Column

First, ensure that your database table includes a deleted_at column. This column will store the timestamp for soft deletes. You can add this column using a migration:

php artisan make:migration add_deleted_at_to_users_table --table=users
    

Then, in the migration file, add the deleted_at column:

public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->softDeletes();
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropSoftDeletes();
        });
    }
    

Run the migration:

php artisan migrate
    

Use the `SoftDeletes` Trait

In your Eloquent model, use the SoftDeletes trait to enable soft deletes:

use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\SoftDeletes;

    class User extends Model
    {
        use SoftDeletes;

        protected $dates = ['deleted_at'];
    }
    

Basic Operations with Soft Deletes

Soft Deleting Records

To soft delete a record, use the delete method:

$user = User::find(1);
    $user->delete();
    

Restoring Soft Deleted Records

To restore a soft-deleted record, use the restore method:

$user = User::withTrashed()->find(1);
    $user->restore();
    

Permanently Deleting Records

To permanently delete a record, bypassing soft deletes, use the forceDelete method:

$user = User::withTrashed()->find(1);
    $user->forceDelete();
    

Querying Soft Deleted Records

By default, soft deleted records are excluded from query results. To include them, use the withTrashed or onlyTrashed methods:

$users = User::withTrashed()->get(); // Includes all records, including soft-deleted ones
    $deletedUsers = User::onlyTrashed()->get(); // Includes only soft-deleted records
    

Soft Deletes in Practice

In a real-world application, soft deletes can be used to implement features like user account deactivation, audit logs, or recovery options. For example, an application might offer users the ability to deactivate their accounts instead of permanently deleting them, providing a period during which they can reactivate their accounts if desired.

Post a Comment

Post a Comment