53

In Laravel, is there a way to differentiate between firstOrCreate creating the row and if finding out the row exists from before?

Or will I have to manually do a get() first, and then create the row?

5

1 Answer 1

124

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, bob@example.

$user = User::firstOrCreate(['email' => '[email protected]']);

// the below will dump out false because this entry already existed
var_dump($user->wasRecentlyCreated);

Now, lets say [email protected] doesn't exist.

$user2 = User::firstOrCreate(['email' => '[email protected]']);

// the below will dump out true because this user was created
// in the current request lifecycle
var_dump($user2->wasRecentlyCreated);
2
  • 9
    That is delicious
    – Dazzle
    May 21, 2020 at 11:02
  • 8
    Brilliant Laravel has everything already covered. May 5, 2021 at 20:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.