Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel foreach "where" with eloquent

I have certain fields and data values which cannot be hardcoded into the query. I'm trying to get something like this:

return Listing::where('id', $id)
            ->where(function($query) use ($input) {
                 ->where('field_1', 'foo_1')
                 ->where('field_2', 'foo_2')
                 ->where('field_3', 'foo_3') 
            }
            ->get();

**Here's what I have **

    return Listing::where('id', $id)
        ->where(function($query) use ($input) {
            $i = 0;
            foreach ($input as $key => $value) {
                $i++;
                // ->where('field_1', red_1); // Desired output
                ->where("where(field_{$i},".$value."_1)");
                // $query = $query."where(field_{$i},".$value."_1)"."<br>";
                // return $query prints out the following
                /*
                    field_1 red_1,
                    field_2 foo_1,
                    field_3 bar_3
                */
            }
        })
        ->get();
like image 796
Amila Jack Avatar asked Dec 20 '22 09:12

Amila Jack


1 Answers

Something like this should work:

$listing = Listing::where('id', $id);
foreach ($input as $key => $value) {
     $i++;
     // ->where('field_1', red_1); // Desired output
     $listing->where("where(field_{$i},".$value."_1)");
}
$results = $listing->get();
like image 121
Alexander Kerchum Avatar answered Mar 23 '23 08:03

Alexander Kerchum