Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

thewebartisan7's avatar

Get all morph relations

I have a model that has morph relations with others models.

When I query this model I get an error when morph relations is stored in database, but not related model.

So I need to add whereHasMorph()

Example:

$myModel = MyModel::query()

            // If morphable was deleted but still in database table of MyModel 

            ->whereHasMorph('morphables', [ MyMorphable1::class,  MyMorphable2::class, etc... ])

This solve issue, but I need to know in advance which are all Morphable models.

Is there a way to know dynamically which are all morphed classes?

Below create a query like so:


select * from `mymodels` where (

(`mymodels`.`mymorphable_type` = 'morphable1' and exists
 (select * from `morphables1` where `mymodels`.`mymorphable_id` = `morphable1`.`id` and `morphable1`.`deleted_at` is null)) 
or
 (`mymodels`.`mymorphable_type` = 'morphables2' and exists
 (select * from `morphables2` where `mymodels`.`mymorphable_id` = `morphables2`.`id` and `morphables2`.`deleted_at` is null)) 
or 
( etc... for each morphables ))

) 

 and `mymodels`.`deleted_at` is null limit 20

If possible to avoid this query would be good. Maybe there are not any other way..

I know that I could just pay attention and soft delete or delete both model in the same time, but I am not sure to leave without this check which would cause issue if for some reason one is deleted or missing and other not.

Thanks

0 likes
1 reply

Please or to participate in this conversation.