The Laravel has a Feature calling for Soft Deleting (logical deletion) that allows one to delete a record logically without deleting it from the database.
For Laravel to recognize a record as deleted it is necessary that:
- the table contains the field
deleted_at
(of the kind TIMESTAMP
);
- the Model use a trait
Illuminate\Database\Eloquent\SoftDeletes
- add yourself to the property
$dates
of the Model the value 'deleted_at'
That way the records that have the field 'deleted_at' IS NOT NULL
. Will be considered excluded records and will not be included in the results of Eloquent.
If it is necessary to show all records, including "deleted", the following method can be used:
<?php
// Todos Models
App\Model::withTrashed()->all();
// Apenas excluídos
App\Model::onlyTrashed()->all();
See the Docs for more information.
Class example:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Exemplo extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
}
Example of Migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateExemploTable extends Migration
{
public function up()
{
Schema::create('exemplo', function (Blueprint $table) {
$table->primary('id');
// ...
$table->softDeletes();
});
}
public function down()
{
}
}
A tip, create a field, Exp:
hidden
like Boolean, ai if you want to delete from the view is just set to true, and list in your view more or less like this:$books->isHidden(false);
– MarceloBoni