Home / Snippets / How to Check if Related Model Exists in Laravel
How to Check if Related Model Exists in Laravel cover

How to Check if Related Model Exists in Laravel

3.7K

3 years ago

0 comments

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');
}
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