In this tutorial, i would like to show you how to use soft delete in laravel. here i will give you example of laravel soft delete. you can use eloquent soft delete in laravel 6, laravel 7 and laravel 8 project.
i will explain you step by step implementation of soft delete in laravel application. we have to use soft delete for safety and backup in laravel.
How work soft delete, laravel add deleted_at column on the table that be default will be null and when we remove then it will place current timestamp, Laravel Model always fetch that record have only deleted_at = null.
Soft Deleting in Laravel
So, how to use in our project, so first when you create table migration then you have to add softDeletes(). you can see like bellow example of migration.
Migration Example:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateItemsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('items', function(Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('description');
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop("items");
}
}
Ok, now you can find deleted_at column in your items table and you have also model should look like as bellow:
Items Model
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Item extends Model
{
use SoftDeletes;
public $fillable = ['title','description'];
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
}
Now, you can use Item model as normally like you use before, you get all record like this way.
$data = Item::get();
To determine if a given model instance has been soft deleted, use the trashed
method:
if ($data->trashed()) {
//
}
It will return all record that have deleted_at = null only and you can also remove record like this way:
$data = Item::find(1)->delete();
You can also get deleted records with soft delete.
$data = Item::withTrashed()->get();
or
$data =
$item->history()->withTrashed()->get();
Retrieve only soft deleted models:
$items= App\Models\Item::onlyTrashed()
->where('teste', 1)
->get();
To restore a soft deleted model into an active state, use the restore
method on a model instance:
$item->restore();
To quickly restore multiple models.
App\Models\Item::withTrashed()
->where('teste', 1)
->restore();
Like the withTrashed
method, the restore
method may also be used on relationships:
$flight->history()->restore();
To permanently remove a soft deleted model from the database, use the forceDelete
method:
// Force deleting a single model instance...
$flight->forceDelete();
// Force deleting all related models...
$flight->history()->forceDelete();