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


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)) {

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

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.

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


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

Sponsors 👑

+ Add Yours