How to restore deleted records in laravel

In laravel you can restore the deleted records. Laravel uses the $table->softDeletes(); in the migration file to delete and restore the deleted records.

Answers 3
  • Restore all deleted records of table in laravel

    //Inside controller’s method
    User::onlyTrashed()->restore();
    
    0

    You can restore all the deleted records of the table using onlyTrashed()->restore() method in laravel. 

  • Restore multiple records after soft-deletes using where condition

    App\Models\Post::onlyTrashed()->where('user_id', 1)->restore();
    
    0

    It will restore all deleted records from the posts table where the value of column user_id equals to 1.

  • Restore a specific deleted record using id in Laravel 8

    //routes\web.php
    Route::get('/restore-record/{id}', [App\Http\Controllers\UserController::class, 'restoreRecord'])->name('restoreRecord');
    
    //Controller's method
    public function restoreRecord($id){
        $restoreUser = User::withTrashed()->find($id);
        if($restoreUser && $restoreUser->trashed()){
            $restoreUser->restore();
        }
    }
    
    
    0

    Laravel can restore the deleted records. You have to use $table->softDeletes(); in your migration file while creating the table structure which creates the deleted_at column in your table. After deleting the record you can use the restore() method on the model object to restore the deleted records in laravel.

  • Back to code snippet queries related laravel