0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel データベースの論理削除

Posted at

はじめに

  • Laravel で データベースの論理削除を行いたい時は、ソフトデリート の機能が使用できる。
  • 論理削除とは、本当にデータベースから削除するのではなく、フラグなどを立ててシステム上から見えなくすること
  • Laravelでは Eloquent の機能でソフトデリートが使用できる。

前提

Laravel のバージョン

$ php artisan -V
> Laravel Framework 5.8.16

Mysql のバージョン

  • mysql を使用する
mysql> select version();
+-----------+
| version() |
+-----------+
| 5.7.28    |
+-----------+

使いかた

①テーブルに『deleted_at』カラムを追加する

  • ここでは users テーブルにソフトデリートを実装する
mysql> describe users;
+-------------------+---------------------+------+-----+---------+----------------+
| Field             | Type                | Null | Key | Default | Extra          |
+-------------------+---------------------+------+-----+---------+----------------+
| id                | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| username          | varchar(20)         | NO   | UNI | NULL    |                |
| password          | varchar(128)        | NO   |     | NULL    |                |
| created_at        | timestamp           | YES  |     | NULL    |                |
| updated_at        | timestamp           | YES  |     | NULL    |                |
| deleted_at        | timestamp           | YES  |     | NULL    |                |
+-------------------+---------------------+------+-----+---------+----------------+

②ソフトデリートを使用できるようにモデルで宣言

  • モデルで宣言するだけで、delete()処理を実行するとdeleted_atカラムに現在の時刻がセットされる。
  • deleted_atカラムに現在の時刻がセットされていると、削除済み隣、クエリ結果に含まれない。
app/Model/User.php
<?php

namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;
省略

まとめ

  • とても簡単にソフトデリートを有効にできた。
  • ソフトデリート済みのデータのみ取得や、物理削除の方法もあるがあとで、別途調べるよお。
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?