Skip to content

[12.x] Adding support for specific events to Event::defer() #56566

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

Merged
merged 1 commit into from
Aug 6, 2025

Conversation

dbpolito
Copy link
Contributor

@dbpolito dbpolito commented Aug 6, 2025

As a continuation of #56556, a good point was raised: #56556 (comment)

Which on second though the idea to being able to set specific events to defer, so now:

Event::defer(function () {
    $parent = Parent::create();
    $parent->children()->create();
}, ['eloquent.created: '.Parent::class]);

Parent::created(function ($model) {
    $parent->children()->count(); // 1
});

That way, other events like creating will still be triggered, being able to have more control and avoid unexpected behavior.

@dbpolito dbpolito mentioned this pull request Aug 6, 2025
@donnysim
Copy link
Contributor

donnysim commented Aug 6, 2025

One of my first ideas was if an event could have a Deferrable or NonDeferrable attribute, until I remembered that a lot of laravel events are just pure strings which is why I withheld suggesting it, but maybe could be an avenue to explore in the future. Unless maybe a pattern matching could be defined for string events like maybe Event::defineNonDeferrable('eloquent.creating: *'), but it would make sense, in my opinion, to have Model creating, updating etc. non-deferrable by default, as they can also prevent creating or updating a Model.

@dbpolito
Copy link
Contributor Author

dbpolito commented Aug 6, 2025

I like the pattern matching idea... not sure about globally defining it... Let's wait for more feedback

@taylorotwell taylorotwell merged commit d83b9f5 into laravel:12.x Aug 6, 2025
62 checks passed
@AhmedAlaa4611
Copy link
Contributor

@dbpolito Hello, can you document the Deferred Events new concept?

@cosmastech
Copy link
Contributor

Do you think there would be an easy way to only defer -ed events? so creating, which may modify an attribute before it's saved, would pass through, but created would wait until the defer block is complete?

I don't think I have a use case for this in mind just yet, however, I would think about something like Spatie's medialibrary, which only creates the UUID on the model creating event. Obviously, this is a bit of a relic, given that we have HasUuids trait now, but nonetheless, seems like it could give some developers headaches.

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.

5 participants