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

377

3 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

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