Back to Course |
Laravel 11 Eloquent: Expert Level

find(), all(), first() and Their Extra Options

Let's talk about all() and first() methods of Eloquent. They have different parameters and kinds of advanced features.


So typically, if we launch all(), for example, from Tinker, it returns all the models.

In this case, there are three users in the database. Did you know you can specify the fields? The all() method accepts an array of fields to be returned.


Next, instead of all(), we can use find() to find a specific object. In the find() method, you specify the primary key value, ID, by default.

Did you know you can specify columns as a second parameter?

Also, you can specify an array of primary keys. This way, it will return a collection instead of an object.


Another well-known and well-used method is findOrFail(), which means that it tries to find the records with provided keys, and if it doesn't find it, it throws an Exception.

That Exception would be rendered as a "404 not found" page by default in the browser. In Tinker, it would just throw a ModelNotFoundException. Laravel automatically returns 404 status as an API response if it happens within your API. Or you can override the Exception and perform some other operation in your Exception settings.

Also, you can have not only findOrFail() but firstOrFail(). For example, you have a where() statement with firstOrFail(). If it finds the user, it returns it.


There are also less-known methods like firstOr(), and then you can provide a callback function to perform whatever you want. For example, instead of 404, throw a different status error.

Similarly, you can do findOr() and the second parameter a closure.