Search code examples
ormlaravelrelationshipseloquent

Laravel adding/finding relationships for relationships


How to find relationships for relationships with Eloquent ORM? Currently I have something like this. Simple relationship. I can find Image and it's photographer. Now I need to do something more complex, I need to find also photographers tags.

dump looks like this

object(Image) {
    ["attributes"] => [],
    ["relationships"] =>
        ["photographer"] =>
            ["attributes"] => [],
            ["relationships"] =>
}

But I need to add tags relationship so It would look like this

object(Image) {
    ["attributes"] => [],
    ["relationships"] =>
        ["photographer"] =>
            ["attributes"] => [],
            ["relationships"] =>
                ["tags"] =>
                    ["attributes"] => [],
                    ["relationships"] =>
}

How is that possible?

/Image model

public function photographer()
{
    return $this->belongs_to('Photographer');
}

public function tags()
{
    return $this->has_many_and_belongs_to('Tag', 'tag_relationships');
}

/Controller

$images = Image::with(['photographer'])->order_by('updated_at', 'desc')->get();

Solution

  • you just use laravel's dot syntax:

    Image::with(['photographer', 'photographer.tags', 'photographer.tags.categories]) ....