Posts Learn Components Snippets Categories Tags Tools new 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

641 views

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.
<?php

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

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for Laravel Eloquent Check Nested Relation Exists

)