Posts Learn Components Snippets Categories Tags About

Laravel Eloquent Check Nested Relation Exists

Learn how to check if nested relation exist in Laravel eloquent with has method

Created on Aug 02, 2021


To check if a nested eloquent relationship exists in Laravel, you can use "has()" method available from the model instance. The nested level can go multi-layers deep inside and you can write the code like below.

Laravel Eloquent Check for Nested Relation
Imagine you have a "Post" model that has a "Comments" relation which then has a "Likes" relation, you can do the checking as follows.

Post::has('comments.likes')->get(); // the post has "comments" and "likes"

Do note that the relationship has to be defined as "hasMany".
Post => hasMany Comments
Comment => hasMany Likes

Snippets by

PostSrc poster


Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

Load comments for Laravel Eloquent Check Nested Relation Exists


PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets