Kārlis Janisels
Kārlis Janisels

Reputation: 1295

How to use Laravel Eloquent class as a variable and loop over to perform the same query for all models

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

Answers (2)

Marcin Nabiałek
Marcin Nabiałek

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

EchoAro
EchoAro

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

Related Questions