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

chadhutchins's avatar

How to Cast a Model to Different Model based on Field

Ex. I have a main Food Model. Then I have abstract classes Fruit, Meat, etc. I also have more specific classes that extend the abstract classes. Ex. Ribeye extends Meat, Apple extends Fruit.

My foods table looks something this: (sorry for the formatting, markdown for tables doesn't seem to work)

id class name ext1 ext2 ext3

1 App\Fruits\Apple apple 5 10 3

2 App\Meats\Ribeye meat 10 10 1

3 App\Meats\Filet meat 8 7 10

Where ext1, ext2, ext3 mean different things for each model.

There are cases in my app where all I have is a food id. So currently I have to do something like this to ultimately return the correct model:

$food = App\Food::find($id);
$food = $food->class::find($id);

I'm guessing this does two separate queries even though it's the same underlying data (not sure on that). But either way it doesn't feel right.

Is there a why to cast the first $food variable to the correct class? Or maybe there's a chain call to cast to another class?

Need something like:

$food = App\Food::find($id)->cast($this->class);

Other option would be to break out the Food types into different tables, but I want to stay away from that if possible.

Thoughts? Thanks!

0 likes
1 reply
ftiersch's avatar

I don't think that quite exists... But what I could think of would be fill()... So something like:

$food = App\Food::find($id);

$specificFood = new $food->class;
$specificFood->fill($food->all());

(not quite sure if "all" works on models but I'm sure there is a method that gives you an array of all attributes :))

Please or to participate in this conversation.