Posts Learn Components Snippets Categories Tags Tools new About
/

How to Check if Related Model Exists in Laravel

Learn how to check and get any related model that may exist in Laravel Eloquent Model using these several methods and prevent any possible errors that may arise when calling the realtion.

Created on Nov 04, 2021

14 views

Sometimes you might come across a scenario where you directly call Model relationship reference and it doesn't return anything. There are 2 possibilities and they are either having no relationship or maybe you are calling the wrong reference. To check if a model has a relation in Laravel you can make use of the truthy value using "if" statement for simple relationships and using "isNotEmpty()" for multiple relationships.

Checking Related Model For Single Relationship


To check the related model for a single relationship such as hasOne, belongsTo, and morphs you can rely on using the "if" statement and then get the condition based on the "truthy" value.
<?php

$post = Post::first();

if($post->author) {
    dd('this post has an author');
} else {
    dd('this post has no author');
}

Checking Related Model For Multiple Relationship


In the case of multiple relationships such as hasMany, belongsToMany, and morphs you can use "isNotEmpty()" method which will determine whether it has a value or not.
<?php

$post = Post::first();

if ($post->comments->isNotEmpty()) {
    dd('This post has comments');
} else {
    dd('This post has no comments');
}

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

new

PostSrc Code Components

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

View Components
)