I have been using query builder for my project and would like to restore a soft deleted record using query builder.
Restoring a soft deleted model is pretty easy too: User::withTrashed()->where('id', 1)->restore(); This sets the deleted_at column back to NULL and makes it accessible again.
But you can get also soft deleted record using withTrashed() of Laravel Eloquent. It will return all record from table. Item::withTrashed()->get(); You can get only soft deleted row using onlyTrashed() of Laravel Eloquent.
soft deletion (plural soft deletions) (databases) An operation in which a flag is used to mark data as unusable, without erasing the data itself from the database.
To do this we need to open Model file in code editor, where you want to add soft delete. add this line in top of the model file. use Illuminate\Database\Eloquent\SoftDeletes; Now we make or model to use Soft delete.
Look here https://laravel.com/docs/5.6/eloquent#soft-deleting
Restoring Soft Deleted Models Sometimes you may wish to "un-delete" a soft deleted model. To restore a soft deleted model into an active state, use the restore method on a model instance:
$flight->restore();
or
Model::query()->restore();
IF you want to do it manually.. just
Model::whereNotNull('deleted_at')->update([
'deleted_at' => null
]);
What soft deleting does is setting a value to deleted_at
column and then filter records where the deleted_at
column has a value using a global scope.
So to restore a soft deleted record all you have to do is set the deleted_at
column to null.
As you wanted to do it using query builder
DB::table('table')
->where('id', $recordToRestoreId)
->update(['deleted_at' => null]);
If using Eloquent
Model::withTrashed()
->where('id', $recordToRestoreId)
->restore();
or if you have a model instance
$model->restore();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With