Home » Php » php – Laravel firstOrNew how to check if it's first or new?

php – Laravel firstOrNew how to check if it's first or new?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m using Laravel’s function firstOrNew() to create a new user or find and update an existing one.

How can I know, after the object is created, if it existed before or if it’s a new object?

The idea is something like this:

$user = \App\User::firstOrNew([
    'email' => $userData->getEmail(),
    'name' => $userData->getName(),
]);

if ($user->new) { // some way to check
    // user was created now
} else {
    //user already existed
}
How to&Answers:

You can check the exists property on the Model.

if ($user->exists) {
    // user already exists
} else {
    // user created from 'new'; does not exist in database.
}

Answer:

You can check if your user was recently created.

if ($user->wasRecentlyCreated) {
    // new user
} else {
    // user already exists
}

(Source: Thomas Kim from this answer)

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.

Answer:

You can always check for an ID (or any other unique primary key) in the model.

$user = \App\User::firstOrNew([
    'email' => $userData->getEmail(),
    'name' => $userData->getName(),
]);

if($user->id) {
    // The user exists and was retrieved from the database...
}

if (!$user->id) {
    // The user was not found in the database and a new User model was created...
}

It is important to keep in mind that after you persist the model using $user->save(), you will NOT be able to use $user->id to check if it was found in the database or not. This is because Eloquent populates all the attributes of the new model after it is saved.