Reputation: 1295
I have a situation where I have to perform the same query for many models. I was wondering if it would be possible to defy my Eloquent classes in array and then loop the over. Here is a pseidocode:
$models = [Model1, Model2, Model3, Model4];
foreach($models as $model){
$model::where(...)->...
}
Tried several approaches but always ended up with TypeError. Is this even possible and if so - what is the correct approach?
Upvotes: 1
Views: 444
Reputation: 111869
It should work without any problems, for example something like this:
$models = [\App\User::class, \App\Admin::class];
foreach ($models as $model) {
$user = $model::where('email','[email protected]')->first();
}
Upvotes: 3
Reputation: 838
just create a dependency, text ready models
class MyController extends Controller
{
protected $models;
protected $result;
public function __construct(Model1 $model,Model2 $model2){
$this->models[]=>$model1;
$this->models[]=>$model2;
//...
}
pubflic function(){
foreach($this->models as $model){
$this->result[]=$model->where(...)//your code
}
}
}
Upvotes: 0