How to delete a record from a table in the view without deleting from the database

Asked

Viewed 678 times

1

I am developing a system at the didactic level and in my view I have a table that displays the data of an employee registered by the user. In the view has the edit and delete buttons, only that the delete 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 someone help me in how I can do this?

I’m using Laravel 5.6 / PHP 7.2.3 / Mysql

  • 1

    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);

1 answer

2


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()
    {
    }
}
  • Fernando, thank you very much. In case I would put the attribute deleted_at as correct boolen?

  • It’s actually a TIMESTAMP where Laravel tests if he goes NULL is because it was not excluded, and if it is not NULL the field has the date of exclusion. If you look at the Migrations code you’ll see that when it’s called $table->softDeletes() schema Builder creates a TIMESTAMP even.

  • Thanks again, I can understand and I will apply here. Hug.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.