In Eloquent, what is the difference between firstOrCreate, firstOrNew and updateOrCreate?

Laravel

Background

Eloquent has three powerful methods if you want to work with existing data. The three methods are firstOrCreate, firstOrNew, and updateOrCreate. To compound matters, the query builder has it's own method, called updateOrInsert. This article attempts to explain the difference and provides some use cases.

Update 04 May 2023

I'll leave this article here for the quick take, but if you want to rather learn from a master following this link: https://laraveldaily.com/post/eloquent-updateorcreate-firstorcreate-examples

Difference between firstOrCreate and updateOrCreate

First or Create is when there are no records and you want to create one. Update or Create is when there might be an existing record, and you want to rather just update the existing one (or create a new one if an update wasn't possible). This is quite confusing, but read on: If you're working with new records, use `firstOrCreate`. If you're interested in updating existing records, use `updateOrCreate`. NEW = FIRST, EXISTING = UPDATE Models returned by `firstOrNew` has not yet been persisted to the database and you will need to call save manually to persist it. firstOrNew is therefor very similar to firstOrCreate except data bas not been persisted yet.

Example Use Cases

You are processing new applications and want to ensure there are no duplicates. Use: firstOrCreate You are processing new applications, but you want to update the information for existing applications in case it has changed: Use: updateOrCreate

How does this differ from the Query builder?

The query builder only has one method, called updateOrInsert

References