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?

first系メソッド

1
Posted at

LaravelのEloquentには、first() 以外にも特定のユースケースに特化した「first系」のメソッドがいくつか存在する。それぞれの挙動と使いどころを整理した。


1. firstOrFail()

モデルが見つからない場合に null を返すのではなく、ModelNotFoundException を投げる。
主に詳細ページなどで、「データがなければ404エラーを出したい」という場合に利用される。

// 見つからない場合は 404 Not Found 画面へ
$user = User::where('email', $email)->firstOrFail();

2. firstOrCreate()

firstOrNew() と似ているが、見つからなかった場合にその場でデータベースに保存(INSERT)する点が異なる。
「存在しなければ作成し、そのインスタンスを即座に使いたい」場合に最適である。

// なければDBに保存してから返す
$user = User::firstOrCreate(
    ['email' => 'test@example.com'],
    ['name' => 'New User']
);

3. firstWhere()

where(...)->first() のショートハンド(短縮記法)である。
条件が一つだけの場合、コードをより簡潔に書くことができる。

// これらは同じ意味
$user = User::where('status', 'active')->first();
$user = User::firstWhere('status', 'active');

まとめ:使い分けの判断基準

用途に応じて以下のように使い分けるのが一般的である。

メソッド 見つからない時の挙動 主なユースケース
first() null を返す 存在チェックを自分で行う場合
firstOrFail() 例外を投げる 404エラーとして処理したい場合
firstOrNew() 空インスタンスを生成 保存はせず、値をセットして後で保存したい場合
firstOrCreate() DBに保存して生成 即座にレコードを作成したい場合
firstWhere() null を返す シンプルな条件で1件取得したい場合

集計クエリにおいては、前述の通り first() 以外を使うメリットはほぼないが、通常のレコード操作においてはこれらのメソッドを使い分けることで、条件分岐の少ない綺麗なコードが書けるようになる。

他にも、特定のカラムの値だけを1件取得したい場合に使える value() なども便利だが、まずはこれらの基本を抑えておくのが良い。

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?