Laravel get() vs first() methods

Avatar
Posted by Sarthak Shrivastava
1 month ago

One of my friend called me and said, Hey Sarthak I need your help, I could't find out the problem in my code. Then I go through the codes and found that he was using get method ( to get data from database via model) and that was the mistake, I just changed get to first .

But the question arise, what is the difference between these two and why that code was not working with get but worked perfectly with first.

Take Some Example

Now consider these two codes and their results

First is for get() method

This one below is for first() method


At first look you did't get the difference, but look closely there is a great difference.

get method give a collection and first method give you a model instance.

When we have to use get() and when first()

When you want to get collection of data means, lots of results then use get but if you want to retrieve only one result then use first.

What else first can do.

Ya this gives you only one result from the ocean of data but as the name suggest it will give the first result.

Suppose you have two results from your query then which one will return by this function, so the answer is the first one.

Whatever laravel get at first, it suddenly return that and this is very cool.

You have may Eloquent collection methods, for example you exists() method will return you boolean, if the database has query part or not.

Conclusión

Get() is for lots of data and first() is for single data.

If you have any question then please comment me or email me on sarthak@bitfumes.com

adiós