Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Laravel findorfail example
    Laravel findOrFail Eloquent PHP find method ModelNotFoundException Laravel tutorial Laravel exceptions


Laravel findorfail example


Here are a few examples of how to use the `findOrFail()` method in Laravel:

Basic Example

php
$post = Post::findOrFail(1);
dd($post);

If the record with ID 1 is found, it will be returned. If not, a `ModelNotFoundException` will be thrown[1][2].

In a Controller

php
public function show($id)
{
    $user = User::findOrFail($id);
    return view('users.show', compact('user'));
}

This controller method will fetch the user by the given ID and pass it to the view. If the user is not found, a 404 error will be returned automatically[3].

Handling the Exception

You can catch the `ModelNotFoundException` in your exception handler to customize the response:

php
public function render($request, Exception $e)
{
    if ($e instanceof ModelNotFoundException) {
        return response()->view('errors.404', [], 404);
    }

    return parent::render($request, $e);
}

Now if `findOrFail()` doesn't find a record, a custom 404 view will be rendered[4].

Comparison to `find()`

The `find()` method returns `null` if a record is not found, while `findOrFail()` throws an exception. Using `findOrFail()` can make your code more explicit about the expected behavior when a record is not found[3][5].

In summary, `findOrFail()` is a convenient way to fetch a record by primary key and automatically throw an exception if it doesn't exist, simplifying your controller logic.

Citations:
[1] https://www.youtube.com/watch?v=y0r2diMsyqQ
[2] https://dev.to/codeanddeploy/laravel-8-eloquent-query-find-and-findorfail-example-2jdl
[3] https://blog.codewithdary.com/find-vs-findorfail
[4] https://dev.to/jackmiras/laravels-exceptions-part-3-findorfail-exception-automated-4kci
[5] https://stackoverflow.com/questions/32737812/laravel-5-how-to-use-findorfail-method