Laravel’s Eloquent and firstOrNew

Hey everyone!

This is yet another web dev post and this is gonna be quick and dirty.. It’s regarding Laravel and the Eloquent’s firstOrNew. firstOrNew is like firstOrCreate, but instead of creating an instance in the database, it just retrieves an instance. You must still save it. While using firstOrNew, I came across a situation where I needed to know if the instance was new or retrieved. I had to do some googling and came across an easily solution: use exists. For example:

$user = User::firstOrNew([name => "John Smith"]);
 //It's new.
} else {
 //It's old.

Simple huh? Neat little trick. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *