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:
Illuminate\Database\QueryException: 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?
CodePudding user response:
static::saving(function (self $model) {
if (empty($model->user)) {
$model->forceFill(['user' => $model->email]);
}
});
CodePudding user response:
Use [Laravel's Mutator][1] for this:
public function setUserAttribute($value)
{
if(empty($value){
$this->attributes['user'] = $this->attributes['email'];
}
}
[1]: https://laravel.com/docs/8.x/eloquent-mutators#defining-a-mutator
CodePudding user response:
I think you should use updating
instead of creating
public static function boot()
{
parent::boot();
self::updating(function ($model) {
if (empty($model->user)) {
$model->user = $model->email;
}
});
}