In addition to findOrFail(), there's also Eloquent method firstOrFail() which will return 404 page if no records for query are found.
$user = User::where('name', 'codimth')->firstOrFail();
What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray() in Laravel:
-
find($id)
takes an id and returns a single model. If no matching model exist, it returnsnull
. -
findOrFail($id)
takes an id and returns a single model. If no matching model exist, it throws an error 404. -
first()
returns the first record found in the database. If no matching model exist, it returnsnull
. -
firstOrFail()
returns the first record found in the database. If no matching model exist, it throws an error 404. -
get()
returns a collection of models matching the query. -
pluck($column)
returns a collection of just the values in the given column. In previous versions of Laravel this method was calledlists
. -
toArray()
converts the model/collection into a simple PHP array.