Ad

Laravel: Detect If Nested Relations Are Loaded

In Laravel we can load model with nested relations

User::with('posts.comments.likes')

But how in other place we can detect if nested relations are loaded? Is there a method?

Model::relationLoaded() detect only direct relation.

public function relationLoaded($key)
{
    return array_key_exists($key, $this->relations);
}
Ad

Answer

It's not possible to get the state of nested relations - at least no other way than iterating through related objects and checking relations individually for each of them.

Good reason why it's not implemented could be the fact, that if the relation is X-to-many, like in your case users can have multiple posts, it is possible to have comments eagerly loaded for only some of the posts in the collection.

Ad
source: stackoverflow.com
Ad