✨ Feat: Add firstOrInsert
method to Query Builder with tests
#54598
+86
−0
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.
This Pull Request introduces a new
firstOrInsert
method to the Laravel Query Builder.The Laravel Query Builder currently lacks a
firstOrInsert
method, unlike Eloquent which offers bothupdateOrCreate
andfirstOrCreate
. WhileupdateOrInsert
is available in the Query Builder, a dedicatedfirstOrInsert
method was missing.This omission has caused confusion and questions in forums, making the Query Builder less intuitive for common "find or create" scenarios. Developers often need a simple way to retrieve an existing record or create a new one if it doesn't exist, without the overhead of Eloquent models.
Implementation
The
firstOrInsert
method is implemented in theIlluminate\Database\Query\Builder
class.It works as follows:
$attributes
usingwhere
andfirst
.insert
, combining the$attributes
and$values
.where
andfirst
and returned.Usage Example
This code will attempt to find a user with the email ‘[email protected]’.
Testing
This PR includes comprehensive unit tests to ensure the functionality and reliability of the firstOrInsert method. Tests cover scenarios for:
Retrieving existing records.
Inserting new records.
Using callable values for dynamic insertion.These tests provide confidence in the correctness of the implementation and will help prevent regressions in future changes.