Check if the Model has a Relationship

If you're working with Eloquent relationships, you might need to check if the model has a relation with another model or not. Thankfully this is pretty simple, even though it might seem more complicated.

The easiest method to do this is to count the model's relationships. The count() can have two types of returns depending on the relationship.

How to check if the Eloquent Model has a relationship with another Model

No matter what kind of relationship we're talking about, you can always use a simple count.

if (count($model->$relation))
	// There is at least one relationship

But what if you want to know how many relations does the model have or how to use it more extensively. There are eight possible results you can get by querying $model->relation or count($model->relation), based on relationship type and number of relations.

If the relation is single (hasOne, belongsTo, morphTo, morphOne), then here's what results you will get.

// no related model
$model->relation; // Returns null
count($model->relation); // Returns 0

// One related model
$model->relation; // Returns an Eloquent model
count($model->relation); // Returns 1

If the relation is one of hasMany, belongsToMany, morphMany, morphToMany, morphedByMany, then here's what results you will get:

// No relation models collection
$model->relation; // Returns a collection with 0 items
count($model->relation); // Returns 0

// One or more related models
$model->relation; // Returns a collection of items
count($model->relation); // Returns the number of items in the collection

In conclusion, if you want to find out if a relation exists or what is the number of existing relations, you should always use count($model->relation).