Meandering Soul

This day is done, I'm going home.
eFranes Penguin Avatar

Deep Linking in Eloquent Models

13
Apr 2015

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
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.

  • Published on April 13, 2015
  • 182 words