加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – Eloquent事件没有解雇

发布时间:2020-12-13 21:58:38 所属栏目:PHP教程 来源:网络整理
导读:我希望在我的用户模型中更改密码时设置密码.所以我正在使用该模型的启动方法: ?phpnamespace AppModel;class User extends IlluminateDatabaseEloquentModel{ protected $table = 'users'; public static function boot() { //die('here'); // this ha
我希望在我的用户模型中更改密码时设置密码.所以我正在使用该模型的启动方法:

<?php
namespace AppModel;

class User extends IlluminateDatabaseEloquentModel
{
    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.

UPDATE – 胶囊初始化

$capsule = new IlluminateDatabaseCapsuleManager;
$capsule->addConnection([
    'driver' => 'mysql','host' => 'localhost','charset' => 'utf8','collation' => 'utf8_unicode_ci','prefix' => '','database' => 'mydb','username' => 'myuser','password' => 'mypass',]);
$capsule->bootEloquent();

解决方法

如果您希望事件起作用,则需要为胶囊设置事件调度程序.

首先,您需要为依赖项添加illuminate / events.在您的composer.json文件中添加“illuminate / events”:“5.2.*”:

"require": {
    // other requires...
    "illuminate/events": "5.2.*"
},

接下来,您需要在胶囊上设置事件调度程序.确保在调用bootEloquent()之前执行此操作.从docs:

// new capsule...

// add connection...

// Set the event dispatcher used by Eloquent models... (optional)
use IlluminateEventsDispatcher;
use IlluminateContainerContainer;
$capsule->setEventDispatcher(new Dispatcher(new Container));

// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$capsule->bootEloquent();

现在你应该好好去.

虽然不相关,但我还想指出你的boot方法应该确保调用parent :: boot();在它做任何其他事情之前(比如设置事件).

可选方案

如果这是您尝试对事件进行的唯一操作,则可以通过为密码属性设置mutator function来完全跳过此操作.每当您为mutated属性赋值(即$user-> password =“hello”)时,都会调用mutator方法.

为此,只需将以下功能添加到您的用户模型:

public function setPasswordAttribute($value) {
    $this->attributes['password'] = bcrypt($value);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读