In my project I need to update member’s user attribute if it’s empty.
I have this code in the model:
class Member extends Model
{
public static function boot()
{
parent::boot();
self::saving(function ($model) {
if (empty($model->user)) {
$model->user = $model->email;
}
});
}
protected $fillable = [
'name',
'email',
'user',
'password',
// ...
];
// ...
}
This is the migration for the model:
Schema::create('members', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email');
$table->string('user');
$table->string('password');
// ...
});
And I try to test it like this:
/** @test */
public function shouldSetUserToEmailIfUserNotSet()
{
$instance = $this->model::factory([
'user' => null
])->create();
$model = $this->model::all()->first();
$this->assertEquals($model->user, $model->email);
}
So the user field is required in the database. And this is the test result:
IlluminateDatabaseQueryException: SQLSTATE[23000]: Integrity constraint violation: 19
NOT NULL constraint failed: members.user (SQL: insert into "members" ("password", "name",
"email", "user", ...
And this error comes from the ->create();
line in the test.
So how should I set the user
attribute on the model before save if it’s not set?
3
Answers
Use [Laravel’s Mutator][1] for this:
I think you should use
updating
instead ofcreating