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

Laravel クエリビルダー更新と取得を1行で済ませる

Posted at

BEFORE:frowning2:

update()の戻り値は通常更新件数(INT型)なので、更新したモデルを返却したい場合取得処理を別で書く必要があります。

class Sample {
  public function sample(mixed $where, array $data): void
  {
    // 1.データ更新
    User::where('column', $where)->update($data);
    // 2.更新データ取得
    $user = User::where('column', $where)->first();
  }
}

AFTER:relaxed:

1行で済ませましょう。
tap()ヘルパー関数を使うことで引数内の戻り値を強制的に返却することができ、update()をチェーンすることで更新したモデルが返却されます。

class Sample {
  public function sample(mixed $where, array $data): void
  {
    // データ更新And取得
    $user = tap(User::where('column', $where)->first())->update($data);
  }
}

引用

Laravel 9.x

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