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:
<?php $user = User::firstOrNew([name => "John Smith"]); if(!$user->exists){ //It's new. } else { //It's old. }
Simple huh? Neat little trick. 🙂