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 returnsnull
.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 returnsnull
.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 calledlists
.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 toarray_map
is not. Similarly, if you type-hint an argument asarray
, PHP won't let you pass it a collection. Newer versions of PHP have theiterable
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
andfirstOrFail
methods is aModelNotFoundException
. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.All information from @Joseph Silber is correct and very useful.
I want to add an answer to list()
From Laravel 5.2 The list method on the Collection, query builder and Eloquent query builder objects have been renamed to pluck. The method signature remains the same.