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.