new-record

Stop checking if record exists: Eloquent methods OrCreate and OrNew

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 povilas@laraveldaily.com (real email, feel free to get in touch!).

Typical code would be:

Now, what if I told you…

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:

But that’s not all! You can do pretty much the same thing for updating the record.

Instead of:

Do this:

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.

Want more tips and articles like this?
20-50 useful links every week on our weekly newsletter - comes out every Thursday!



3 thoughts on “Stop checking if record exists: Eloquent methods OrCreate and OrNew

Leave a Reply

Your email address will not be published. Required fields are marked *