1
2

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 1 year has passed since last update.

Laravel とPHP TipsAdvent Calendar 2023

Day 24

Eloquentのfresh()とrefresh()の違い

Posted at

概要

モデルオブジェクトで使えるfresh()とrefresh()メソッドの違いを記述します。

fresh()

fresh()は、最新のモデルの状態を返却するメソッドです。
メソッドを生やした元のモデルオブジェクトは最新になりません。

$user1 = User::firstWhere('name','John');
$user2 = User::firstWhere('name','John');

$user2->update([
    'name' => 'hoge'
]);

$freshUser = $user1->fresh();
dd($user1->name,$freshUser->name);
// John         hoge

refresh()

refresh()は、メソッドを実行したモデルオブジェクトを最新の状態にします。

$user1 = User::firstWhere('name','John');
$user2 = User::firstWhere('name','John');

$user2->update([
    'name' => 'hoge'
]);

$user1->refresh();
dd($user1->name);
// hoge

参考

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?