laracoft's avatar

Assigning a model in a model method

  1. As an example, I have to write $this->currency_id = $currency->id in my model's method.
  2. Is there a Laravel way to write $this->currency = $currency without have to specify the _id and ->id?
  3. Why do I want to do this? Because if we are in a service/controller, we write $model->currency = $currency and it works, I just want to have a consistent style of assigning models
0 likes
4 replies
kevinbui's avatar

Yes, you can do so by defining a mutator:

class YourModel extends Model
{
    public function setCurrencyAttribute($value)
    {
        $this->attributes['currency_id'] = $value->id;
    }
}
DhPandya's avatar

@laracoft Why aren't you not adding a custom property to your model? $appends. It will help you to add custom properties without modifying the existing ones.

Please or to participate in this conversation.