Search code examples
phplaraveleloquentlaravel-query-builderlaravel-collection

Re-apply laravel where statement in a for each loop


How do i re-apply a where() statement on a certain collection while being in a for each loop.

Im currently looping my parameters and i want to for each them all in a where() statement so i can filter a collection with these where() statements


my foreach here below: it currently is taking all where() results and merges them together, but i want all where() statements to apply to 1 single collection so it filters them out.

        $guides = new Collection;
        foreach($request->query() as $key => $value){
            if($guides->isEmpty()){
                $guides = SupportGuideTranslation::where($key, $value)->get();
            }
            else{
                $guides = $guides->toBase()->merge(SupportGuideTranslation::where($key, $value)->get());
            }
        }
        $guides = $guides->unique();

These are my parameters:

?active=2&language_id=2

This is the result of $request->query():

^ array:2 [▼
  "active" => "2"
  "language_id" => "2"
]

My result now is that i get 6 records back (instead 2).

  • 3 records with language_id=2 and active=1 (Wrong)
  • 1 record with language_id=1 and active=2 (wrong)
  • 2 record with language_id=2 and active=2 (Correct)

What i want is that it only shows the 2 records that follow both parameter rules instead having 2 separate collections merged.


Solution

  • You can add to the QueryBuilder without executing the query, what you are doing is executing one query each iteration. So instead build up the correct query, then execute it.

    $query = SupportGuideTranslation::query();
    
    foreach ($request->query() as $key => $value) {
        $query->where($key, $value);
    }
    
    $translations = $query->get();