Laravel Elequent 模型事件监听的简单使用

本文介绍如何在Laravel中利用Eloquent ORM监听模型的生命周期事件,包括创建、更新、删除等,通过boot方法和观察者模式实现代码的优雅触发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Eloquent 模型会触发许多事件(Event),我们可以对模型的生命周期内多个时间点进行监控。
Laravel Elequent 模型事件可以在模型的生命周期内对以下几点进行监听:
retrievedcreatingcreatedupdatingupdatedsavingsaveddeletingdeletedrestoringrestored。事件能在每次在数据库中保存或更新特定模型类时轻松地执行代码。

从数据库中检索现有模型时会触发 retrieved 事件。当新模型第一次被保存时, creating 以及 created 事件会被触发。如果模型已经存在于数据库中并且调用了 save 方法,会触发 updatingupdated 事件。在这两种情况下,saving / saved 事件都会触发。
对于这些事件的监听,大致有两种方式,一种是使用观察器,另外一种是直接在模型中使用 boot 方法,boot 方法会在用户模型类完成初始化之后进行加载,因此我们对事件的监听可以放在该方法中。

boot 方法
<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

/**
 * App\Models\User
 *
 * @property int $id
 * @property string $name
 * @property string $email
 * @property string $password
 * @property string|null $remember_token
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property-read \Illuminate\Notifications\DatabaseNotificationCollection|\Illuminate\Notifications\DatabaseNotification[] $notifications
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereEmail($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User wherePassword($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereRememberToken($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];


    public function gravatar($size = 100)
    {
        $hash = md5(strtolower(trim($this->attributes['email'])));
        return "http://www.gravatar.com/avatar/$hash?s=$size";
    }

    protected static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub
        static::creating(function ($user) {
            $user->activation_token = str_random(30);
        });

    }
}

观察器

Laravel 没有默认生成观察器的 artisan 命令,你可以将观察器文件放在你喜欢的目录来存放。一般放在 App\Observers 目录下。

  1. 新建观察器文件:
    app/Observers/UserObserver.php
<?php
/**
 * Created by PhpStorm.
 * User: nwei
 * Date: 2019/2/20
 * Time: 10:03
 *
 *    .--,       .--,
 *   ( (  \.---./  ) )
 *    '.__/o   o\__.'
 *       {=  ^  =}
 *        >  -  <
 *       /       \
 *      //       \\
 *     //|   .   |\\
 *     "'\       /'"_.-~^`'-.
 *        \  _  /--'         `
 *      ___)( )(___
 *     (((__) (__)))     高山仰止,景行行止.虽不能至,心向往之.
 */

namespace App\Observers;


use App\Models\User;

class UserObserver
{

    public function creating(User $user)
    {
        $user->activation_token = str_random(30);
    }

}
  1. AppServiceProviderboot 方法中注册观察器
    app/Providers/AppServiceProvider.php
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // 注册观察器
        User::observe(UserObserver::class);
    }

在适合的模型生命周期中,事件监听会自动触发。无需手动调用。

参考
https://learnku.com/docs/laravel/5.5/eloquent/1332#events

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值