Laravel has a feature called Soft Deleting which allows you to logically delete a log 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 type TIMESTAMP
);
- Model use the trait
Illuminate\Database\Eloquent\SoftDeletes
- If you add in the
$dates
property of the Model the value 'deleted_at'
In this way, the records that have the 'deleted_at' IS NOT NULL
field. Excluded records will be considered and will not be included in Eloquent results.
If it is necessary to show all records, including "excluded", you can use the following method:
<?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'];
}
Sample 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()
{
}
}