Skip to content
Advertisement

Laravel Check If Related Model Exists

I have an Eloquent model which has a related model:

JavaScript

When I create the model, it does not necessarily have a related model. When I update it, I might add an option, or not.

So I need to check if the related model exists, to either update it, or create it, respectively:

JavaScript

Where <related_model_exists> is the code I am looking for.

Advertisement

Answer

In php 7.2+ you can’t use count on the relation object, so there’s no one-fits-all method for all relations. Use query method instead as @tremby provided below:

JavaScript

generic solution working on all the relation types (pre php 7.2):

JavaScript

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

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement