How to use soft deletes to mark records as "deleted" without physically removing them from the database using Eloquent in Laravel?

To use soft deletes in Laravel, follow these steps:

Step 1: Add the SoftDeletes Trait Include the SoftDeletes trait in your Eloquent model class. This trait provides the necessary functionality for soft deleting and restoring records. For example:

use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class YourModel extends Model { use SoftDeletes; // Your other model definitions... }

Step 2: Add a deleted_at Column Add a nullable deleted_at timestamp column to the database table associated with the model. This column will store the deletion timestamp for soft deleted records.

You can create this column using a migration. For example:

php artisan make:migration add_deleted_at_to_your_table --table=your_table

Then, update the migration file to include the deleted_at column definition:

use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddDeletedAtToYourTable extends Migration { public function up() { Schema::table('your_table', function (Blueprint $table) { $table->softDeletes(); }); } public function down() { Schema::table('your_table', function (Blueprint $table) { $table->dropSoftDeletes(); }); } }

Finally, run the migration:

php artisan migrate

Step 3: Soft Delete a Record To soft delete a record, you can call the delete() method on an Eloquent model instance. For example:

$record = YourModel::find($id); $record->delete();

This will update the deleted_at column of the record with the deletion timestamp. However, the record will still exist in the database.

Step 4: Retrieve Soft Deleted Records To retrieve the soft deleted records along with the active records, you can use the withTrashed() method. For example:

$records = YourModel::withTrashed()->get();

This will return both the active and soft deleted records.

Step 5: Restore a Soft Deleted Record To restore a soft deleted record, you can use the restore() method on the model instance. For example:

$record = YourModel::find($id); $record->restore();

This will set the deleted_at column of the record to NULL, effectively restoring the record.

Step 6: Permanently Delete a Soft Deleted Record If you want to permanently delete a soft deleted record, you can use the forceDelete() method. For example:

$record = YourModel::find($id); $record->forceDelete();

This will remove the record from the database permanently, without any possibility of restoration.

By using these steps, you can implement soft deletes in Laravel's Eloquent ORM to mark records as "deleted" without physically removing them from the database.