我希望在我的用户模型中更改密码时设置密码.所以我正在使用该模型的启动方法:
<?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...
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
我在模型上使用save()方法在数据库中创建条目,显然这应该触发创建事件.我已经清空数据库表以确保正在创建一个新行(它是),此事件不会触发 - 并且我的密码是未加密的.顺便说一句,我在我的应用程序(不是Laravel)中使用illuminate/database ^ 5.2.
UPDATE - 胶囊初始化
$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();
Run Code Online (Sandbox Code Playgroud)
pat*_*cus 11
如果您希望事件起作用,则需要为胶囊设置事件调度程序.
首先,您需要添加illuminate/events到依赖项.添加"illuminate/events": "5.2.*"到您的composer.json文件:
"require": {
// other requires...
"illuminate/events": "5.2.*"
},
Run Code Online (Sandbox Code Playgroud)
接下来,您需要在胶囊上设置事件调度程序.确保在打电话之前这样做bootEloquent().来自文档:
// 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();
Run Code Online (Sandbox Code Playgroud)
现在你应该好好去.
虽然没有关系,但我还想指出你的boot方法应该确保parent::boot();在它做任何其他事情之前调用(比如设置事件).
可选方案
如果这是您尝试对事件进行的唯一操作,则可以通过为属性设置mutator函数来完全跳过此操作password.只要为mutated属性赋值(即$user->password = "hello"),就会调用mutator方法.
为此,只需将以下函数添加到User模型中:
public function setPasswordAttribute($value) {
$this->attributes['password'] = bcrypt($value);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2084 次 |
| 最近记录: |