php - Can I cast one Eloquent model to another?

In eloquent you can have different models operating on a same table. So, is it possible to switch an object from one Model to another in a runtime. Assuming that we have three classes:
Product extends Model
ProductSet extends Product
SimpleProduct extends Product
The difference between ProductSet and a SimpleProduct is columncomplex
which has 'true' in it for a ProductSet and 'false' for a SimpleProduct.
ProductSet and a SimpleProduct models have Scopes applied to them so thatProductSet::all()
will get only sets, andSimpleProduct::all()
will get only a simple products.
Parent model however allow us to get both types of products viaProduct::all()
so, is it possible to go through all instances of Product class and switch them to their higher level models at runtime based on a value of propertycomplex
?
Answer
Solution:
Since you're already extending the class which holds the same props as the parent. You can loop over anyproduct
collection and get all the attributes throughgetAttributes()
method and pass to the parent. Because each of your model is extending EloquentModel
which accepts attribute in theconstructor
and fills its attribute.
Following example extends the defaultUser
class and converts back to the Parent class
<?php
namespace App;
class Admin extends User {}
Get allAdmins
and convert them toUser
$admins = \App\Admin::all();
$users = [];
foreach ($admins as $admin) {
$users[] = new \App\User($admin->getAttributes());
}
dd(collect($users));
Answer
Solution:
Yes you can do that, Based on the prop you have to create object of that specific class
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: videoxxx
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.