Skip to content

[12.x] Deferred Events #56556

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 3 commits into from
Aug 6, 2025
Merged

[12.x] Deferred Events #56556

merged 3 commits into from
Aug 6, 2025

Conversation

dbpolito
Copy link
Contributor

@dbpolito dbpolito commented Aug 5, 2025

This introduces a new concept: Deferred Events.

Use Cases

When we need to listen do a model event that creates child records, let's think of the following scenario:

$parent = Parent::create();
$parent->children()->create();

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

Currently if you listen for Parent::created, the child will not be available yet, we would need to dispatch a event after the child is created, or dispatch a job and have after commit enabled.

With the new idea:

Event::defer(function () {
    $parent = Parent::create();
    $parent->children()->create();
});

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

This allows us to defer the execution of the events to after the callback is executed, ensuring that all related records are available.

This also might open a lot of other possibilities.

Thoughts?

@taylorotwell taylorotwell merged commit feffcd6 into laravel:12.x Aug 6, 2025
19 of 60 checks passed
@taylorotwell
Copy link
Member

Thanks!

@dbpolito dbpolito deleted the event_defer branch August 6, 2025 15:54
@donnysim
Copy link
Contributor

donnysim commented Aug 6, 2025

I like the idea, but doesn't this create a situation where Model creating event will not be fired? there's a lot of situations where attributes are added or modified on creating, updating etc., and should fire no matter what, so Model wise these deferred events bring a lot of unforeseen problems. Am I missing something or is this unforeseen side of the feature?

@dbpolito
Copy link
Contributor Author

dbpolito commented Aug 6, 2025

True... i think there are situations where it may create some weird behaviors... but i think it feels clear what's going on... you're deferring all events... So use where it makes sense... But i do think it opens a lot of possibilities in several places.

@dbpolito
Copy link
Contributor Author

dbpolito commented Aug 6, 2025

@donnysim on second thought, this gave me the idea of adding a way to whitelist events to defer, which is implemented at #56566

Let's see how this one goes...

AhmedAlaa4611 referenced this pull request in laravel/docs Aug 7, 2025
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.

3 participants