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

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

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets

More