Notes for learning Laravel Events and Observers model Events

Source: Internet
Author: User
Tags bind closure event listener

First, let's look at the technology called model events. Its basic concepts are very simple:

In EventServiceProvider, you can add a specific event listener and bind a closure function.
In a closure function, you can add new behaviors without touching the model code.
The binding operation must be placed in the boot () method of the class.

This is a simple example of binding a created user event to a closure function. The $ user parameter of the closure contains the instance of the specified user:

Public function boot (DispatcherContract $ events)
  {
Parent: boot ($ events );
 
User: created (function ($ user)
      {
// Doing something here, after User creation...
});
  }

As you can imagine, every model has these methods. Therefore, if you want to bind an operation to a saved event, you must:

User: saved (function ($ user)
    {
// Doing something here, after User save operation (both create and update )...
});

Another interesting function is to stop the current operation through the pre-method. In fact, you may use the following method:

Creating
Updating
Saving
Restoring
Deleting

If you want to exit the operation, you can return a Boolean value of false.

Assume that the user's email address ends with @ deniedprovider.com, and we exit the create Operation. You can do this:

User: creating (function ($ user)
    {
If (ends_with ($ user-> email, '@ deniedprovider.com '))
      {
Return false;
      }
});

Obviously, you cannot do this for created, updated, saved, restored, and deleted events. These events have occurred and cannot be returned.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.