laravelframeworksevent-listenerlaravel-9observers

Difference between Events, Listeners, and Observers?


I'm confused about Events, Listeners, and Observers in Laravel.

What is an observer?
What is an event?

How do they differ, and how are they connected?


Solution

  • Observers and events do not behave at all like each other

    Observers are basically predefined events that happen only on Eloquent Models (creating a record, updating a record, deleting, etc). Events are generic, aren't predefined, and can be used anywhere, not just in models.

    Observers:

    An observer watches for specific things that happen within eloquent such as saving, saved, deleting, deleted (there are more but you should get the point). Observers are specifically bound to a model.

    Events:

    Events are actions that are driven by whatever the programmer wants. If you want to fire an event when somebody loads a page, you can do that. Unlike observers events can also be queue, and ran via laravel's cron heartbeat. Events are programmer defined effectively. They give you the ability to handle actions that you would not want a user to wait for (example being the purchase of a pod cast)

    The documentation does a very good job covering these.

    Reference Taken From : https://www.scratchcode.io/laravel/difference-between-events-and-observers-in-laravel/