What is the difference between these methods:
find()
findOrFail()
first()
firstOrFail()
get()
list()
toArray()
I've been using them and each one gives a different result and sometimes I need to add toArray()
at the end of get()
because my function is expecting an array. Won't the other methods produce arrays as well?
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.