Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Events vs Observers in laravel

Tags:

I'm really confused with events and observers. because both are doing same things. what are the differences b/w events and observers? Thanks in advance.

like image 744
Suresh Kumar Avatar asked Nov 14 '18 10:11

Suresh Kumar


People also ask

What are the observers in Laravel?

According to the Laravel framework's documentation: If you are listening for many events on a given model, you may use observers to group all of your listeners into a single class. Observers classes have method names which reflect the Eloquent events you wish to listen for.

What is the difference between event and observer?

Simple Difference Between Events and ObserversObservers 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.

What is difference between event and job in Laravel?

You may consider jobs as something that needs to be executed in order for your application to work properly. Events are mostly side effects/results of those actions - while important and useful, they play a secondary role.

What is model observer in Laravel 8?

Laravel Observers are used to group event listeners for a model eloquent. Laravel Observers will listener event for model eloquent method like create, update and delete. Retrieved: after a record has been retrieved. Creating: before a record has been created.


1 Answers

Observers and events do not do the same thing at all.

Simple Difference

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/

like image 153
Mayank Dudakiya Avatar answered Sep 20 '22 18:09

Mayank Dudakiya