Home / Snippets / Laravel Eloquent Check Nested Relation Exists
Laravel Eloquent Check Nested Relation Exists cover

Laravel Eloquent Check Nested Relation Exists

1.9K

3 years ago

0 comments

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
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this