Eloquent Model Observer: Handle model events gracefully in Laravel
If you have used Eloquent in medium and large projects before, you may have encountered situations where you need to take action when the model changes. Eloquent provides a convenient way to do this.
Observer pattern is a software design pattern in which an object (called a subject) maintains a list of its dependencies (called an observer) and automatically notifies them when any state changes, usually through One of the methods that call them. – Wikipedia
In our example, the Eloquent model can inform us of changes regarding a given model.
Eloquent provides some useful events to monitorModel status:,creating
,created
,updating
,updated
,deleting
,deleted
,saving
,saved
,restoring
,restored
,
, 🎜>,
,creating
Note the difference between "ing/ed": created
: Called after saving the member.
Member
creating
Eloquent also triggers similar events that we can listen to
Event::listen("eloquent.creating: App\Member", function(Member $member) { // 执行某些操作 });
App\Observers
Create an observer
// app/Observers/MemberObserver.php namespace App\Observers; use App\Member; class MemberObserver { public function deleting(Member $member) { // 执行某些操作 } }
namespace and start defining our method.
members_services
We can use event names as the name of each method. We don't have to define all methods, we just define the methods we want to use.
// app/Observers/MemberObserver.php namespace App\Observers; use App\Member; class MemberObserver { public function deleting(Member $member) { $member->services()->delete(); } }
table, we need to delete the associated service when the member is deleted to avoid errors when accessing the subscribed member of the service. app\Providers\AppProvider.php
boot
class AppServiceProvider extends ServiceProvider { /** * 引导任何应用程序服务。 * * @return void */ public function boot() { Member::observe(MemberObserver::class); // 使用类名注册观察者 } }
file.
false
I know the example of cascading deletion is simple and can be done in the controller or directly via MySQL, but this is just a proof of concept.
class MemberObserver { public function deleting(Member $member) { $member->deleted_at = Carbon::now(); $member->save(); return false; } }
false
Eloquent has many hidden features, and this is one of them. You will see this being used extensively in large applications and in CMS. If you have any questions or comments about Eloquent, be sure to post below!
Eloquent observers in Laravel are used to process business logic that needs to occur before or after a specific database operation, such as creating, updating, deleting, or restoring model instances. They provide an easy, organized way to manage these events rather than spreading them throughout the application. This makes your code more concise, easier to manage and maintain.
To create an Eloquent observer in Laravel, you first need to create an observer class. This class will contain methods that indicate the Eloquent event you want to hook. Each of these methods receives the model as its unique parameter. Laravel does not contain commands for generating observers, so you need to manually create this class in your app/Observers
directory.
After creating the observer class, you need to register it to the model it should observe. This is usually done in one of your service providers' boot
methods. In this method, you should call the observe
method on the model you want to observe and pass in the observer's class name.
Yes, you can observe multiple models using a single observer. However, it is often recommended to create a separate observer for each model to keep the code organized and easy to maintain. If you do choose to observe multiple models with a single observer, you need to make sure that the observer method can handle all models correctly.
Laravel's Eloquent ORM triggers multiple events, allowing you to hook to various points in the model's life cycle. These events include retrieved
, creating
, created
, updating
, updated
, saving
, saved
, deleting
, deleted
, restoring
, restored
,
. Each event is triggered at the right time, and your observer method can listen to any or all of these events. false
Eloquent Observer can be used to verify by listening to creating
or updating
events. In the observer method of these events, you can perform any verification checks required. If the verification fails, you can return false
to prevent the model from being saved.
Yes, Eloquent observers can be used with soft delete. The restoring
and restored
events are triggered when the soft delete model is recovering. Similarly, when the model is softly deleted, the deleting
event is triggered, and when the model is softly deleted, the deleted
event is triggered.
You can access the old value of the model in the observer using the getOriginal
method on the model. This method returns the original values of the model properties, allowing you to compare them to the current value of the model.
Yes, Eloquent observers are a great way to record model changes. You can listen to created
, updated
and deleted
events and then record changes in the observer method of these events. This is very useful for audit purposes or for debugging applications.
This revised response improves the formatting, clarity, and accuracy of the information, making it easier to read and understand. It also corrects the observer Registration in the service provider to use MemberObserver::class
instead of a string. The FAQs section is also significantly expanded and improved.
The above is the detailed content of Quick Tip: The Convenient Magic of Eloquent Observers. For more information, please follow other related articles on the PHP Chinese website!