Posts Learn Snippets Categories Tags About
/

How to Check If Relationship Exists In Laravel 8

Learn how to check if relationship exists in Laravel 8 to prevent an error

Created on Jul 09, 2021

11 views

Checking whether a relationship exists or not is very important before accessing any of its properties. There are several ways to do so and below are the examples.

One to One
To check if there's a "one to one" relationship record, you can make use of the "isset" method when calling the relation.
if (isset($post->author)) {
    dd($post->author);
}

One to Many
Since one to many is usually tied to "collection" you can make use of the "isEmpty" or "isNotEmpty" method.
if (isset($post->comments->isNotEmpty())) {
    dd($post->comments);
}

if (isset($post->comments->isEmpty())) {
    dd('There are no comments');
}

Optionally you can make use of the "optional" helper method to safely access any of the relationship properties. For the example below, if the "name" property exists and has value it will be returned, otherwise "null" value will be returned.
optinal($post->author)->name

Created 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.