Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restore a soft deleted record using Laravel's Query builder?

I have been using query builder for my project and would like to restore a soft deleted record using query builder.

like image 444
Prashanth Avatar asked Mar 28 '18 15:03

Prashanth


People also ask

Which of the following is correct way to retrieve Soft Deleted models?

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.

How can I get soft deleted data in Laravel?

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.

What is a soft delete?

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.

How do I add a soft delete to an existing table?

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.


2 Answers

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
]);
like image 101
ZeroOne Avatar answered Oct 21 '22 09:10

ZeroOne


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();
like image 28
chanafdo Avatar answered Oct 21 '22 08:10

chanafdo