Home / Snippets / How to Check If Relationship Exists In Laravel 8
How to Check If Relationship Exists In Laravel 8 cover

How to Check If Relationship Exists In Laravel 8

2.9K

3 years ago

0 comments

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