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

When updating related entities, Eloquent events such as saved and updated are NOT fired. #3

Open
sto-calcueasy opened this issue Oct 13, 2020 · 1 comment

Comments

@sto-calcueasy
Copy link

Hi Alfa,

This is Stefan. This is my first time submitting an issue for your package.

The problem

When using the update() method without retrieving the entity first, the Laravel events updating, updated, saving and saved are not fired. I noticed this when I was working on an Event for my application and I was wondering why the saved event was only fired when a new related entity is added, but it is not fired when an existing entity is edited.

$this->getRelated()->where($relatedKeyName, $castKey(array_get($row, $relatedKeyName)))
->update($row);

The reason why saved event is fired when a new related entity is added is because createMany method is used.

$newRecords = $this->createMany($newRows);

Possible solution?

I would solve the issue by replacing the use of update method with

$related = $this->getRelated()
                    ->where($relatedKeyName, $castKey(array_get($row, $relatedKeyName)))
                    ->first()
                    ->fill($row)
                    ->save();

Literature

https://laravel.com/docs/8.x/eloquent#updates
https://stackoverflow.com/questions/41295032/laravel-eloquent-model-update-event-is-not-fired

What do you think?

Please let me know what do you think. If you are not OK with the change, would it be OK for me to make a fork?

Thank you very much for the package. It is really handy.

Best regards!

@korridor
Copy link

korridor commented Mar 4, 2021

@sto-calcueasy This repository has been inactive for a while. I created a fork that can be installed directly with composer, works with newer Laravel version and added unit tests.
Link to the fork: https://github.com/korridor/laravel-has-many-sync

I also corrected the problem that you are referring to for updates.

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

No branches or pull requests

2 participants