9850830247 info@fairshare.tech

Introduction

Laravel provides methods by which one can mark a record in a database for deletion or to temporarily prevent it from being selected. This is soft-deleting feature of Laravel. In order to actually delete the record, a “hard” delete or “permanent” delete function must be performed.

 

Objective

This document aims to provide a step by step approach to implement Laravel soft delete functionality. After going through this document, one should be able to successfully implement “soft delete” in laravel

 

What is soft deleting?

  • Opposite of hard/physical delete. It means records are not physically deleted from database.
  • A ‘deleted_at’ attribute is set on the model and inserted into the database.
  • A timestamp is set on the deleted_at column.
  • If a model has a non-null deleted_at value, the model has been soft deleted.

 

How to enable in Laravel?

  • use or import the Illuminate\Database\Eloquent\SoftDeletes trait on the model.
  • In the model, add the deleted_at column to your $dates property.
  • use SoftDeletes trait in the model.
  • Add the ‘deleted_at’ column to your database table. The Laravel schema builder contains a helper method to create this column:
  • Schema::table(‘flights’, function (Blueprint $table) {
    $table->softDeletes();
    });
  • <?php
    namespace App;
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\SoftDeletes;
    class Flight extends Model
    {
    use SoftDeletes;

        /**
         * The attributes that should be mutated to dates.
         *
         * @var array
         */
        protected $dates = [‘deleted_at’];
    }

How to use it?

  • When the delete method is called on the model, the deleted_at column will be set to current date and time.
  • When a model that uses soft deletes is queried, the soft deleted records will be automatically excluded in the query results. .

 

Various methods related to soft delete

  • trashed(): Detemines if a model instance has been soft deleted

if ($flight->trashed()) {
//
}

  • withTrashed(): This method forces soft deleted records to appear in a result

$flights = App\Flight::withTrashed()
->where(‘account_id’, 1)
->get();

  • onlyTrashed(): This method will retrieve only soft deleted records

$flights = App\Flight::onlyTrashed()
->where(‘airline_id’, 1)
->get();

  • restore(): This un-deletes the soft deleted record i.e., restores the soft deleted record into ‘active’ state.

App\Flight::withTrashed()
->where(‘airline_id’, 1)
->restore();

  • forceDelete(): Permanently removes a soft deleted record.

 

Conclusion

Soft delete feature is a very useful feature of Laravel. This feature helps us to retrieve a record from database in case if a wrong record was deleted from the user interface. Implementing this is Laravel by following the above steps is really easy.

 

References

 

How can I help?
Powered by Fair Share