Veur's avatar
Level 2

Get a model by `model_type` & `model_id` (polymorphic relation)

I have a Polymorphic Relation in which I store the *_type and the *_id, for example:

model_type = 'App\Models\Post' model_id = 1

Is there a Laravel (helper) function to get an Eloquent instance of this Post with id 1?

0 likes
5 replies
Tray2's avatar
Tray2
Best Answer
Level 73

Just use a simple where

->where([ 
		['model_type',  '=',  'App\Model\Post' ],
		[ 'model_id', '=', 1]
])
Veur's avatar
Level 2

That's indeed the way I'm doing it now, and it works. But I expected there to be an easier way, like:

$post = resolve('App\Models\Post', 1)::with('notes');

for example

Please or to participate in this conversation.