20
19

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のEloquentでカラムの変更情報を取得

Posted at

カラムが変更されたか判断する必要があり、動作を確認したメモ。

>>> $group = App\Group::all()->last();
=> App\Group {#49052
     id: 10,
     name: "Aグループ",
     mailaddress: "hoge@example.com",
     prefectures_id: 13,
     city: "千代田区",
     address: "大手町一丁目",
     telephone: "03XXXXXXXX",
     created_at: "2019-01-09 12:09:56",
     updated_at: "2019-01-09 12:09:56",
   }

値を変更してみる

>>> $group->name = "hoge";
=> "hoge"
>>> $group->telephone = "03YYYYYYYY"
=> "03YYYYYYYY"

isDrityメソッドで確認。変更されてるのでtrueですね。

>>> $group->isDirty();
=> true

カラム絞っても確認できます。

>>> $group->isDirty("name");
=> true
>>> $group->isDirty("city");
=> false
>>> $group->isDirty(["name", "city"]);
=> true

変更された内容はgetDirtyメソッドで確認。
変更されたnameとtelephoneの内容が確認できる。

>>> $group->getDirty();
=> [
     "name" => "hoge",
     "telephone" => "03YYYYYYYY",
   ]

変更前の値が知りたい場合にはgetOriginalメソッド

>>> $group->getOriginal();
=> [
     "id" => 10,
     "name" => "Aグループ",
     "mailaddress" => "hoge@example.com",
     "prefectures_id" => 13,
     "city" => "千代田区",
     "address" => "大手町一丁目",
     "telephone" => "03XXXXXXXX",
     "created_at" => "2019-01-09 12:09:56",
     "updated_at" => "2019-01-09 12:09:56",
   ]
>>> $group->getOriginal("name");
=> "Aグループ"

saveしてみる。
isDirtyはfalseを返すようになり、getOriginalで確認しても更新後の値に書き換わっている。

>>> $group->save();
=> true
>>> $group->isDirty();
=> false
>>> $group->getOriginal("name");
=> "hoge"
20
19
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
20
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?