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