How to delete a record from a table in the undeleted view of the database

1

I'm developing a system at didactic level and in my view I have a table that displays the data of an employee registered by the user. In the view you have the edit and delete buttons, but deleting it is also deleting the the record in the database. To maintain data integrity I need to delete only the employee in the view for the user and keep the record saved in the database.

Can anyone help me on how I can do this?

I'm using Laravel 5.6 / PHP 7.2.3 / MySQL

    
asked by anonymous 05.09.2018 / 21:25

1 answer

2

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()
    {
    }
}
    
05.09.2018 / 21:36