php - Eloquent event is not firing -
i want set password when changes in user model. i'm using boot method of model:
<?php namespace app\model; class user extends \illuminate\database\eloquent\model { protected $table = 'users'; public static function boot() { //die('here'); // happens user::saving(function ($user) { //die('here'); // doesn't happen if ($user->isdirty('password')) { $user->password = // hash password... } }); } }
i'm using save() method on model create entry in data base, apparently should fire creating event. i've emptied database table ensure new row being creating (it is), event not fire - , password raw un-ecrypted. way, i'm using illuminate/database ^5.2 in app (not laravel).
update - capsule initialization
$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();
if want events work, need setup event dispatcher capsule.
first, need add illuminate/events
dependencies. add "illuminate/events": "5.2.*"
composer.json
file:
"require": { // other requires... "illuminate/events": "5.2.*" },
next, you'll need setup event dispatcher on capsule. make sure before call booteloquent()
. docs:
// new capsule... // add connection... // set event dispatcher used eloquent models... (optional) use illuminate\events\dispatcher; use illuminate\container\container; $capsule->seteventdispatcher(new dispatcher(new container)); // setup eloquent orm... (optional; unless you've used seteventdispatcher()) $capsule->booteloquent();
now should go.
while not related, wanted point out boot
method should make sure call parent::boot();
before else (like setting events).
optional solution
if thing you're trying events, can skip altogether setting mutator function password
attribute. mutator method called time assign value mutated attribute (i.e. $user->password = "hello"
).
to this, add following function user
model:
public function setpasswordattribute($value) { $this->attributes['password'] = bcrypt($value); }
Comments
Post a Comment