1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Laravel】get()・first()で0件データを綺麗に処理する方法

Last updated at Posted at 2025-07-25

やっほ〜、泉(@izumin_0401)だよ〜

今回は、Laravelのget()・first()で0件データを綺麗に処理する方法について、サクッと解説していきやす。

ブログ記事はこちら

first()でnullを適切に処理する方法

Laravelのfirst()は、データが見つからない場合にnullを返すため、適切なnullチェックが必要です。

最もスマートな方法は、firstOrFail()やOptional Chainingを活用することです。

firstOrFail()を使えば、データが見つからない場合に自動的に404エラーを返してくれるため、コントローラーでの例外処理が不要になります。

// Bad: 手動でnullチェックする方法
$user = User::where('email', $email)->first();
if (!$user) {
    abort(404, 'ユーザーが見つかりません');
}

// Good: firstOrFail()を使う方法
$user = User::where('email', $email)->firstOrFail();
// データが見つからない場合は自動的に404エラーが返される

get()で空のコレクションを判定する方法

get()は常にコレクションを返すため、isEmpty()やisNotEmpty()を使った判定が効果的です。

また、count()よりもisEmpty()の方がパフォーマンス面で優れています。

空の場合に代替データを返したい時は、whenEmpty()が便利です。

// Bad: count()を使った判定
$users = User::where('status', 'active')->get();
if (count($users) === 0) {
    return '該当ユーザーなし';
}

// Good: isEmpty()を使った判定
$users = User::where('status', 'active')->get();
if ($users->isEmpty()) {
    return '該当ユーザーなし';
}

// Better: whenEmpty()を使った方法
$users = User::where('status', 'active')->get();
return $users->whenEmpty(function () {
    return collect(['該当ユーザーなし']);
});

まとめ

Laravelのget()・first()で0件データを綺麗に処理する方法について解説しました。

役に立ったら「いいね」ボタンをポチッとお願いします🙏

最後に

Twitterも見てね。

Vlogも見てね。

仮想通貨のサイトも見てね。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?