The first() method will return only one record, while the get() method will return an array of records that you can loop over. Also, the find() method can be used with an array of primary keys, which will return a collection of matching records.
find($id) takes an id and returns a single model. If no matching model exist, it returns null . findOrFail($id) takes an id and returns a single model.
The Laravel Eloquent first() method will help us to return the first record found from the database while the Laravel Eloquent firstOrFail() will abort if no record is found in your query. So if you need to abort the process if no record is found you need the firstOrFail() method on Laravel Eloquent.
Sometimes you may wish to throw an exception if a specific record is not found. To do this, you may use the findOrFail method in Laravel findOrFail method and generates and exception if specific record is not found.
find($id)
takes an id and returns a single model. If no matching model exist, it returns null
.
findOrFail($id)
takes an id and returns a single model. If no matching model exist, it throws an error1.
first()
returns the first record found in the database. If no matching model exist, it returns null
.
firstOrFail()
returns the first record found in the database. If no matching model exist, it throws an error1.
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 called lists
.
toArray()
converts the model/collection into a simple PHP array.
Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.
Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach
loop is ok, put passing it to array_map
is not. Similarly, if you type-hint an argument as array
, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable
typehint, which can be used to accept both arrays and collections.
If you ever want to get a plain array from a collection, call its all()
method.
1 The error thrown by the findOrFail
and firstOrFail
methods is a ModelNotFoundException
. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.
Probably things changed but the findorFail method can take 2 arguments: $id
and $columns
mixed/array params respectively. Passing a second arg is not required. That said, this would work:
$post = Post::findOrFail([1,2], ['title', 'subtitle']);
If one of the $ids
fails, the ModelNotFoundException
with message 'No query results for model ... ' will be thrown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With