How to add foreach inside query with WHERE condition in Laravel

Code Example:

//Filter with client data and client name
$clientData = array();

$clientData = array(
                  array('client_id' => 10001, 'client_name' => 'amazon'),
                  array('client_id' => 10002, 'client_name' => 'flipkart'),
                  array('client_id' => 10005, 'client_name' => 'alibaba')
            );

//query to fetch equivalent
$result = DB::table('client_list')
	    ->select('*')
	    ->where(function($query) use ($clientData){
	    foreach ($clientData as $key => $client) {
		if ($key == 0) {
	            $query->where('client_id', $client['client_id']);
		    $query->where('client_name', $client['client_name']);
		} else {
		    $query->orWhere('client_id', $client['client_id']);
		    $query->where('client_name', $client['client_name']);
		}
	     }
	   })
	   ->orderBy('id', 'desc')
	   ->get();			

print '<pre>'; print_r($result);	//print result value

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *