RednBlack RednBlack - 12 days ago 7
PHP Question

Laravel get model id inside setAttribute

I have model like this where i want to get a attribute inside SetFooAttribute. but all time $this->getAttribute('id') is empty! is there a way to access id ?

class MyModel extends Model
{

public static function boot()
{
parent::boot();

static::created(function($model)
{
$model->uuid = Uuid::generate(4)->string;
$model->save();
});
}

public function setFooAttribute($value)
{
$this->attributes['foo'] = $value.'-'.$this->getAttribute('id');
}

Answer

You should use getKey() method to get the value of the model's primary key. Use it like $this->getKey()

Comments