Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here
Tutorial Free

Stop checking if record exists: Eloquent methods OrCreate and OrNew

December 27, 2017
2 min read
Another "hidden gem" of Laravel which is surprisingly rarely used or even known, though it's mentioned in the official Eloquent documentation. Imagine that you have a record, and you need to check if that record already exists in the database - to prevent duplicate, you wouldn't save it second time. There's an elegant way to perform it in Eloquent. Let's take an example - a user with email [email protected] (real email, feel free to get in touch!). Typical code would be:
$user = User::where('email', '[email protected]')->first();
if (!$user) {
  $user = User::create([
    'email' => '[email protected]',
    'first_name' => 'Povilas',
    'last_name' => 'Korop',
  ]);
}
Now, what if I told you...
$user = User::firstOrCreate(['email' => '[email protected]'],
  ['first_name' => 'Povilas', 'last_name' => 'Korop']);
Yup, it's that easy. This sentence performs the same thing - checks the user by email, and if it doesn't exist - creates the record, filling the extra fields with the array in the second parameter. There's also a method called firstOrNew(). It works almost identically to firstOrCreate(), except that it doesn't actually create a record in DB - it just returns a new Eloquent model object which then you can modify before saving:
$user = User::firstOrNew(['email' => '[email protected]'],
  ['first_name' => 'Povilas', 'last_name' => 'Korop']);
// ... Some more manipulation on $user
$user->save();
But that's not all! You can do pretty much the same thing for updating the record. Instead of:
$user = User::where('email', '[email protected]')->first();
if ($user) {
  $user->update([
    'first_name' => 'Povilas',
    'last_name' => 'Korop',
  ]);
} else {
  $user = User::create([
    'email' => '[email protected]',
    'first_name' => 'Povilas',
    'last_name' => 'Korop',
  ]);
}
Do this:
$user = User::updateOrCreate(['email' => '[email protected]'],
  ['first_name' => 'Povilas', 'last_name' => 'Korop']);
Same logic of parameters here - Laravel will check for email field, and if it finds the record, it will get updated with first_name and last_name, otherwise new entry will be created with all those three fields. Some more info and a different example - in the official Eloquent documentation.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.