DEV Community

AquaCat
AquaCat

Posted on

【Laravel】How to delete record logically

There are 2 ways to delete records from tables.

  1. Physical deletion is to literally delete records from your database and there is no way to restore it. In SQL, you code something like;
DELETE FROM books WHERE author_id=2;
Enter fullscreen mode Exit fullscreen mode

("Delete the record from the table 'books' whose 'authoer_id' is 2.")

  1. Logical deletion is to that you actually keep the record. However, by setting a specified column (usually, setting to 1 (or true) from 0 (or false)), you can make the record disappear from the table. In SQL, you code something like;
UPDATE books SET delete_flg = 1 WHERE author_id=2;
Enter fullscreen mode Exit fullscreen mode

("In 'books' table, update 'delete_flg' in (a) column(s) whose 'author_id' is 2.)

So, you still see the record in the table.
If you want to get all records from books, you can code;

SELECT * FROM books WHERE delete_flg = 0;
Enter fullscreen mode Exit fullscreen mode

Then you get all books that are not deleted logically.

3.How do you delete logically in Laravel?
In migration file, you need to code as below;

 public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->bigIncrements('id')->comment('ID');
            $table->bigInteger('author_id')->nullable()->default(null)->comment('Author for the book');
            $table->softDeletes();
//Or you can code as below instead of '$table->softDeletes().'
            $table->timestamp('deleted_at')->nullable()->default(null)->comment('logical deletion flag');
        });
    }
Enter fullscreen mode Exit fullscreen mode

Then in a Model file,

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Book extends Model
{
    //Add
    use SoftDeletes;
}

Enter fullscreen mode Exit fullscreen mode

If you "delete" data by using Eloquent as below, for example,

Book::where('author_id',2)->delete();
Enter fullscreen mode Exit fullscreen mode

you still see the record in your database, but it is logically deleted.

Top comments (0)