How to check if related model exists in Laravel

Published on Author Code Father

since @TheShiftExchange did not take the advice, there we go with generic solution working on all the relation types:

if (count($model->relation))
{
  // exists}

This will work for every relation since dynamic properties return Model or Collection. Both implement ArrayAccess.

So it goes like this:

single relations: hasOne / belongsTo / morphTo / morphOne

// no related model
$model->relation; // null
count($model->relation); // 0 evaluates to false

// there is one
$model->relation; // Eloquent Model
count($model->relation); // 1 evaluates to true

to-many relations: hasMany / belongsToMany / morphMany / morphToMany / morphedByMany

// no related collection
$model->relation; // Collection with 0 items evaluates to true
count($model->relation); // 0 evaluates to false

// there are related models
$model->relation; // Collection with 1 or more items, evaluates to true as well
count($model->relation); // int > 0 that evaluates to true

First suggested solution wouldn’t work for the former relations, since there is no count()methods on the model, and simple if ($model->relation) wouldn’t evaluate to false for any of the latter relations, since there is always a Collection. And that, even empty, always evaluates to true.

Comments

comments