Eloquent 模型会触发许多事件(Event),我们可以对模型的生命周期内多个时间点进行监控。
Laravel Elequent 模型事件可以在模型的生命周期内对以下几点进行监听:
retrieved
、creating
、created
、updating
、updated
、saving
、saved
、deleting
、deleted
、restoring
、restored
。事件能在每次在数据库中保存或更新特定模型类时轻松地执行代码。
从数据库中检索现有模型时会触发 retrieved
事件。当新模型第一次被保存时, creating
以及 created
事件会被触发。如果模型已经存在于数据库中并且调用了 save
方法,会触发 updating
和 updated
事件。在这两种情况下,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 目录下。
- 新建观察器文件:
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);
}
}
- 在
AppServiceProvider
的boot
方法中注册观察器
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