Home / Snippets / How to Check if Model Doesn't Have Relation in Laravel
How to Check if Model Doesn't Have Relation in Laravel cover

How to Check if Model Doesn't Have Relation in Laravel

347

2 years ago

0 comments

To check whether a model has a relation or not in Laravel, you can make use of the "has()" and "doesntHave()" methods available to every Laravel model.

Check Model has() Relation
To check if a model has a relation you can make use of this method like below. Imagine you want to know whether a post has a comment, if it does then eager load it together.
<?php

$postHaveComments = Post::has('comments')
    ->with('comments')
    ->get();

Check Model doesntHave Relation
To check if a model doesn't have a relation, then you can write it like below. The query will return only the model that doesn't have a comments.
<?php

$postHasNoComments = Post::doesntHave('comments')
    ->get();
notion avatar

Ahmad Aziz

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 ☕️

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this