Wednesday, November 16, 2016

Quick Tip: The Convenient Magic of Eloquent Observers

If you've used Eloquent on medium to large projects before, you may have encountered a situation where you want to take action when something happens to your models. Eloquent provides a convenient way to do so.

Laravel Logo

The Observer Pattern

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. - Wikipedia

In our case, Eloquent models can notify us about changes on a given model.

Model Events

Eloquent provides a handful of useful events to monitor the model state: creating, created, updating, updated, deleting, deleted, saving, saved, restoring, restored.

Notice the "ing/ed" difference.

  • creating: Called before saving the new member.
  • created: Called after saving the member.

Eloquent also fires similar events that we can listen for. The below example attaches a listener to the creating event on the Member model.

Event::listen("eloquent.created: App\\Member", function(Member $member) {
    // do something
});

Continue reading %Quick Tip: The Convenient Magic of Eloquent Observers%


by Younes Rafie via SitePoint

No comments:

Post a Comment