Skip to content

[9.x] Fix inconsistent results of firstOrNew() when using withCasts()#41257

Merged
taylorotwell merged 3 commits into
laravel:9.xfrom
Attia-Ahmed:fix_inconsistent_results_of_firstOrNew
Feb 28, 2022
Merged

[9.x] Fix inconsistent results of firstOrNew() when using withCasts()#41257
taylorotwell merged 3 commits into
laravel:9.xfrom
Attia-Ahmed:fix_inconsistent_results_of_firstOrNew

Conversation

@Attia-Ahmed

Copy link
Copy Markdown
Contributor

The issue is when using withCasts to override model casts, leads to inconsistent results when using firstOrNew method or any similar method depends on Model::newInstance() such as firstOrCreate(), updateOrCreate. the results are differ depends on whether the element exists on DB or not, as one result of Model $casts and other form withCasts().

For example:
If we have a Model with $casts = ['time' => 'datetime'];
and by running these queries:

$result1 = Model::query()->withCasts(['time' => 'string'])
    ->firstOrCreate(['time' => '07:30']);

$result2 =Model::query()->withCasts(['time' => 'string'])
    ->firstOrCreate(['time' => '07:30']);

both queries will leads to different entries on database as under the hood where method is looking for time = 07:30 and fail to find one, then newInstance() method will create new instance with datetime cast, so the next query will fail to find time = 07:30 and this behavior will remain for every use of firstOrCreate unless there is an existent entire in DB matches the attribute.

So developer won't be able to depend on firstOrCreate, updateOrCreate or firstOrNew to have consistent and unique data in the database in such cases.

I have started with failing tests to prove the issue, and end up with solving it by modifing newInstance method to fill model attributes after mergeCasts.

@Attia-Ahmed
Attia-Ahmed force-pushed the fix_inconsistent_results_of_firstOrNew branch from 2a85586 to a26bde4 Compare February 25, 2022 22:05
@taylorotwell
taylorotwell merged commit ee00c09 into laravel:9.x Feb 28, 2022
@Attia-Ahmed
Attia-Ahmed deleted the fix_inconsistent_results_of_firstOrNew branch March 1, 2022 06:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants