skip to Main Content

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


  1. static::saving(function (self $model) {
      if (empty($model->user)) {
       $model->forceFill(['user' => $model->email]);
       }
    });
    
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
  3. 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;
                }
            });
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search