Posts Learn Components Snippets Categories Tags Tools About
/

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

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

Created on Jul 23, 2021

361 views

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();

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

)