LoginSignup
0
0

More than 3 years have passed since last update.

Laravel Eloquent 論理削除

Last updated at Posted at 2020-07-24

Laravel Eloquentで論理削除を行う手順

Eloquentで論理削除(Soft Delete)を行う手順

手順概要

  1. マイグレーションファイルの編集。
  2. モデルの編集。
  3. コントローラーの編集。

手順詳細

マイグレーションファイルの編集

テーブル作成のコードに「$table->softDeletes();」を追記。

[コード例]

migtation
public function up()
{
    Schema::create('tablename', function (Blueprint $table) {
        $table->id();
        $table->string('name', 50);
        $table->string('tel', 13);
        $table->timestamps();
        $table->softDeletes();
    });
}

※この記述でテーブルに「deleted_at」が追加されます。

モデルの編集

対象となるモデルに
「use Illuminate\Database\Eloquent\SoftDeletes;」
「use SoftDeletes;」
を追記。

[コード例]

Model
namespace App;

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

class Modelname extends Model
{
    use SoftDeletes;
}

コントローラーの編集

あとは、コントローラーで削除すれば、論理削除が実行されます。

[削除コード例]

controller
Modelname::find($id)->delete();

※削除してもレコードは残り、「deleted_at」に削除日時が挿入されます。
※「deleted_at」が入力されたレコードはget等で取得されません。

0
0
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
0