Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.8] Make updateExistingPivot() safe on non-existent pivot #29362

Merged
merged 1 commit into from
Aug 1, 2019
Merged

[5.8] Make updateExistingPivot() safe on non-existent pivot #29362

merged 1 commit into from
Aug 1, 2019

Conversation

mpyw
Copy link
Contributor

@mpyw mpyw commented Aug 1, 2019

Fixes issue from [5.8] Fix many to many sync results with custom pivot model by themsaid · Pull Request #28416 · laravel/framework.

Currently, when we use updateExistingPivot() with a custom pivot class, the following code will be executed.

$updated = $this->getCurrentlyAttachedPivots()
    ->where($this->foreignPivotKey, $this->parent->{$this->parentKey})
    ->where($this->relatedPivotKey, $this->parseId($id))
    ->first()
    ->fill($attributes)
    ->isDirty();

However, it is unsafe; If we call updateExistingPivot() for non-existent record, it will unexpectedly cause FatalThrowableError.

Symfony\Component\Debug\Exception\FatalThrowableError: Call to a member function fill() on null
  File "/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php", line xxx

This PR resolves this issue by fixing like this:

$pivot = $this->getCurrentlyAttachedPivots()
    ->where($this->foreignPivotKey, $this->parent->{$this->parentKey})
    ->where($this->relatedPivotKey, $this->parseId($id))
    ->first();

$updated = $pivot ? $pivot->fill($attributes)->isDitry() : false;

@mpyw mpyw marked this pull request as ready for review August 1, 2019 10:31
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