LoginSignup
155
150

More than 5 years have passed since last update.

[Laravel] ソフトデリートと取得、復元、完全削除

Posted at

物理削除と論理削除

データベースの削除には物理削除と論理削除があります。言葉はどうでもいいのですが、2つには大きな違いがあります。
それは、復元可能かどうかということです。
この復元可能な削除、いわゆるゴミ箱に入っている状態にする削除方法が論理削除でソフトデリートになります。

とりあえずデータベースを作る

データベースを作っていきましょう。

php artisan make:migration create_contents_table --create=contents

ここではcontentsテーブルを作成しています。

create_contents_table.php
    public function up()
    {
        Schema::create('contents', function (Blueprint $table) {
            $table->increments('id');
            $table->text('body');
            $table->timestamps();

            $table->softDeletes();
        });
    }

textデータ型で、bodyカラムを作っている単純なデータベースです。
最後の$table->softDeletes();がポイントです。
このテーブルの要素に削除処理をするときはソフトデリートだよと、定義しています。

付随したモデルを作る

次に、データベースに付随したモデルを作りましょう。

php artisan make:model Content
Content.php
use Illuminate\Database\Eloquent\SoftDeletes;

class Content extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];

    protected $fillable = [
        'body'
    ];
}

モデルでは、$fillableでbodyをいじれるように設定しています。
use SoftDeletes でソフトデリートを使用できるようにしており、削除した日がわかるように$datesでdeleted_atカラムを作成しています。

ここまできたらmigrateしましょう。

php artisan migrate

中身が空なのでデータを入れる

現在は中身が空なので適当にデータを3つぐらい入れてみましょう。

web.php

use App\Content;

Route::get('/contents/insert', function() {
    Content::create([
        'body' => 'Laravel is PHP framework!!',
    ]);
});

Route::get('/contents/insert2', function() {
    Content::create([
        'body' => 'PHP is programming language!!',
    ]);
});

Route::get('/contents/insert3', function() {
    Content::create([
        'body' => 'programming is a lot of fun!!',
    ]);
});

これで指定のURLにアクセスするとデータが入ります。

image.png

いけてますね。deleted_atは現在NULLになっています。

ソフトデリートと取得

本題のソフトデリートをしてみましょう。

web.php
Route::get('/contents/softdelete', function() {
    Content::find(1)->delete();
});

idが1の要素を削除します。

image.png

いけましたね。削除した日が表示されておりデータベースにはあるけど取得はできません。

次は削除した要素を取得しましょう。

web.php
Route::get('/contents/softdelete/get', function() {
    $content = Content::onlyTrashed()->whereNotNull('id')->get();

    dd($content);
});

image.png

いけていますね。

他のメソッドも紹介

onlyTrashed()は削除済みの要素のみ取得するメソッドですが他のメソッドもあります。
また完全削除や、復元のメソッドも紹介します。

//削除済みのデータも含める
Content::withTrashed()->whereNotNull('id')->get();

//完全削除
Content::onlyTrashed()->whereNotNull('id')->forceDelete();

//復元
Content::onlyTrashed()->whereNotNull('id')->restore();

まとめ

早くlaravelを使いこなせるようになりたいです。。。

155
150
2

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
155
150