Laravel firstOrNew how to check if it's first or new?
firstOrNew()
This function will either return the first record from the database, or instantiate a new model instance that does not yet exist in the database. Therefore, if you'd like to check if the instance was pulled from the database or if it is a new instance, you can check the exists
property (not function) on the model.
if ($user->exists) {
// user already exists and was pulled from database.
} else {
// user created from 'new'; does not exist in database.
}
The original question was about firstOrNew()
, but a lot of people seem to come here for firstOrCreate()
, as well. firstOrCreate()
is different, and requires a different check.
firstOrCreate()
This function will either return the first record from the database, or create a new record in the database and return that. Since a newly created record would exist in the database, you can't check the exists
property, because it'll be true in both instances. However, you can check the wasRecentlyCreated
property. This property will be true if the current model instance was just created in the database, or false if it was already in the database.
if ($user->wasRecentlyCreated) {
// user just created in the database; it didn't exist before.
} else {
// user already existed and was pulled from database.
}
You can check if your user was recently created.
if ($user->wasRecentlyCreated) {
// new user
} else {
// user already exists
}
(Source: Thomas Kim from this answer)
If you created the model in the current lifecycle, then the model's wasRecentlyCreated attribute will be set to true. Otherwise, that attribute will be set to false.
In other words, lets say you have a user with the email, [email protected]
$user = User::firstOrCreate(['email' => '[email protected]']);
var_dump($user->wasRecentlyCreated);
// the above will dump out false because this entry already existed otherwise true.