Using findorFail() and firstOrFail() method

Without findorFail() method we need to implement like following snippet

$post = Post::find(12333);

if(!$post) {
  abort(404);
}


We can implement the above code in one line like below

$post = Post::findOrFail(1);


For both the cases above, laravel will show 404 error in the page as find query did not find the given post id from database. This default 404 page also can be customized.

There is another method firstOrFail() which we can implement like below to achieve the same result above in one line

$post = Post::where('id',1)->firstOrFail();

Related Posts


Using WhereIn

Updating multiple rows

Using Like

Using orWhere

What is Query Builder?

Using "with" in eloquent query

Getting last inserted id

Selecting last row of a table

Using parameters in find() method

Using local scope in eloquent

Using global scope in eloquent