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

findOrFail() の使い方と find() との違い

Last updated at Posted at 2025-03-22

① findOrFail() とは?

  • Eloquentモデルで、主キー(通常は id)でレコードを取得するメソッド。
  • 該当データがない場合、例外 (ModelNotFoundException) を自動で投げる。

②基本的な使い方

$user = User::findOrFail($id);
  • $id に一致するレコードを users テーブルから取得。
  • データが存在しないと、自動で 404エラーページ が表示される(Laravel標準)。

③find() との違い

  • find($id)
    → nullを返す(処理は継続)

  • findOrFail($id)
    → 例外をスロー
    → 自動で404エラー

④使い分けの考え方

  • find()を使う場面
    → 「レコードがなくても処理を続けたい」とき
$user = User::find($id);
if ($user) {
    // ロジック実行
} else {
    // 自前でエラー表示や処理分岐
}
  • findOrFail() を使う場面
    → 「レコードがなければ処理を止めたい」とき(特にコントローラー内で便利)
$user = User::findOrFail($id); // 存在しないと404
return view('users.show', compact('user'));

⑤エラーの種類とcatch例

  • 例外クラス:Illuminate\Database\Eloquent\ModelNotFoundException

use Illuminate\Database\Eloquent\ModelNotFoundException;

try {
    $post = Post::findOrFail($id);
} catch (ModelNotFoundException $e) {
    abort(404, '指定された投稿が見つかりませんでした');
}

⑥ルーティングと連携する使い方(ルートモデルバインディング)

Route::get('/users/{user}', [UserController::class, 'show']);
public function show(User $user)
{
    // 自動的に findOrFail してくれる!
    return view('users.show', compact('user'));
}

⑦まとめ

  • findOrFail() は「レコードが存在しない」ことを前提に考えるべき場面で便利
  • バグを減らし、安全にコーディングしたい場合におすすめ
  • find() との違いを明確に理解して、場面に応じて使い分けよう
0
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
0
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?