Add saveOrIgnore Eloquent Model method for conflict-safe inserts#59026
Open
antonkomarev wants to merge 2 commits intolaravel:13.xfrom
Open
Add saveOrIgnore Eloquent Model method for conflict-safe inserts#59026antonkomarev wants to merge 2 commits intolaravel:13.xfrom
antonkomarev wants to merge 2 commits intolaravel:13.xfrom
Conversation
Contributor
Author
|
And yes, we can make it right now with query builder, but I want to have elegant API, same as default creation. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
When creating records with unique constraints,
save()throwsUniqueConstraintViolationException:Current workarounds are verbose and suboptimal:
Solution:
saveOrIgnore()Uses the SQL-level
INSERT ... ON CONFLICT (columns) DO NOTHING RETURNING *— no exceptions, no extra queries:Use Cases
1. Idempotent event handlers
2. Race-condition-safe registration
3. One-time actions / feature flags
4. Conditional logic based on insert result
API Properties
bool—trueif inserted,falseif conflictsaving,creating,created,saved), timestamps, unique IDscreated/savedevents do NOT fire,existsstaysfalseRETURNINGclauseCurrent Limitations
Not all databases suported
UPDATE not available
saveOrIgnore()throwsLogicExceptionif called on an existing model ($model->exists === true).The UPDATE path is intentionally not supported because
UPDATEmodifies existing rows and does not create new ones, so unique constraint conflicts on the target columns can only occur if you are changing a unique column's value to one that already exists in another row. This is a fundamentally different (and rare) scenario that should be handled explicitly, not silently ignored.AFAIK, PostgreSQL does not support it; SQLite does.
Possible methods naming