Deep Linking in Eloquent Models

  • Reading time: 1 min
  • Published 8 years ago

Sometimes, when designing data models, it turns out that access to a property of a related model might be handy from the current model. For the case of one-to-many relations, Laravel’s Eloquent already comes with the hasManyThrough()-method. But what if it’s a one-to-one relation? And what if the attribute one wants to have access to is up a few levels in the model hierarchy? Well, turns out that can be pretty easily done, too.

Assuming, three models A, B, C all related, e.g. B has a_id, C has b_id and C would benefit from direct access to A, that can be achieved through Eloquent with the following code:

class C extends Model
{
    ...

    public function b()
    {
        return $this->belongsTo('B');
    }

    public function a()
    {
        return $this->belongsTo('A');
    }

    public function getAIDAttribute()
    {
        return $this->b->a_id;
    }

    ...
}

Of course, one might also use this to fetch a specific attribute instead of creating a complete relation. Keep in mind though, that this may cause serious performance issues since the ORM has to fetch all referenced entities before it can return anything.