In php 7. 2+, you cannot use count for a relationship object, so there is no universal method for all relationships. Instead, use a query method like @tremby below:
$model->relation()->exists()
universal solution that works with all types of relations ( pre php 7.2 ):
if (count($model->relation)) {
This will work for every relationship since dynamic properties return a Model or Collection . Both implement ArrayAccess .
So it looks like this:
single relationships: 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
relationship to many: hasMany / belongs to 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
Jarek Tkaczyk May 28 '14 at 12:45 2014-05-28 12:45
source share