我想在我的用户模型中更改密码时设置密码。所以我正在使用模型的引导方法:
<?php
namespace App\Model;
class User extends \Illuminate\Database\Eloquent\Model
{
protected $table = 'users';
public static function boot()
{
//die('here'); // this happens
User::saving(function ($user) {
//die('here'); // this doesn't happen
if ($user->isDirty('password')) {
$user->password = // hash password...
}
});
}
}
我在模型上使用 save() 方法在数据库中创建条目,显然这应该触发创建事件。我已经清空了数据库表以确保正在创建一个新行(它是),此事件不会触发 - 我的密码是未加密的原始密码。顺便说一句,我在我的应用程序(不是 Laravel)中使用 illuminate/database ^5.2。
更新 - 胶囊初始化
$capsule = new Illuminate\Database\Capsule\Manager;
$capsule->addConnection([
'driver' => 'mysql',
'host' => 'localhost',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'database' => 'mydb',
'username' => 'myuser',
'password' => 'mypass',
]);
$capsule->bootEloquent();
最佳答案
如果你想让你的事件正常工作,你需要为胶囊设置一个事件调度器。
首先,您需要将illuminate/events
添加到您的依赖项中。将 "illuminate/events": "5.2.*"
添加到您的 composer.json
文件中:
"require": {
// other requires...
"illuminate/events": "5.2.*"
},
接下来,您需要在胶囊上设置事件调度程序。确保在调用 bootEloquent()
之前执行此操作。来自docs :
// new capsule...
// add connection...
// Set the event dispatcher used by Eloquent models... (optional)
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
$capsule->setEventDispatcher(new Dispatcher(new Container));
// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$capsule->bootEloquent();
现在你应该可以开始了。
虽然不相关,但我还想指出您的 boot
方法应该确保在执行任何其他操作之前调用 parent::boot();
(例如设置事件)。
可选解决方案
如果这是您尝试对事件做的唯一事情,您可以通过设置 mutator function 来完全跳过这一步。为您的 password
属性。每当您为已更改的属性(即 $user->password = "hello"
)赋值时,都会调用更改器方法。
为此,只需将以下函数添加到您的 User
模型中:
public function setPasswordAttribute($value) {
$this->attributes['password'] = bcrypt($value);
}
关于php - Eloquent 事件没有触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35261924/