Laravel – re-assign relationships in updates

Alternate title: Stop stuffing around with entity_id.

Working on a project with a representative – a user who looks after the company.

When changing the representative, I want to supply the whole representative to the update method – e.g. $customer->representative is an object with an id, name, etc. It’s just a pointer, but it means less double handling to send in the object.

I do not want to extract the ID from the object that the user supplied and pass that to the controller.


In the Company model, we need a ‘setRepresentativeAttribute’ method. This extracts the ID and puts it in the representative_id column.

    public function setRepresentativeAttribute($value)
    {
        $this->attributes['representative_id'] = $value['id'];
    }

Instead of making sure representative_id is fillable, we now need to make sure representative is fillable on the model.

protected $fillable = ['representative']; //not representative_id

It’s a simple pattern, but also one I’ve implemented the long way in the past.