php – Eloquent事件没有解雇

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – Eloquent事件没有解雇脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望在我的用户模型中更改密码时设置密码.所以我正在使用该模型的启动方法

<?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.

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();

解决方法

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

首先,您需要为依赖项添加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 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来完全跳过此操作.每当您为mutated属性赋值(即$user-> password =“hello”)时,都会调用mutator方法.

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

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

脚本宝典总结

以上是脚本宝典为你收集整理的php – Eloquent事件没有解雇全部内容,希望文章能够帮你解决php – Eloquent事件没有解雇所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。