koushiki
koushiki

Reputation: 9

Invalid argument supplied for foreach() issue in laravel

My query in controller page

$d= "DB::table('users')->where('gender',$gender)";    
if(!empty($age)){
$d.= "->where('age','>',$age)";
}    
$d.="->paginate(20)";

if age is not empty that time only want add age to the query. but query showing Invalid argument supplied for foreach() error. Without double quotes query running but unable to avoid empty age variable.

Upvotes: 0

Views: 47

Answers (2)

Prashant Deshmukh.....
Prashant Deshmukh.....

Reputation: 2292

Shorter version

 $d = DB::table('users')->where('gender',$gender); 

 $d = empty($age) ? $d->paginate(20) : $d->where('age','>',$age)->paginate(20);

Upvotes: 1

Thai Nguyen Hung
Thai Nguyen Hung

Reputation: 1212

Please try it:

$d = DB::table('users')->where('gender',$gender);    
if(! empty($age)) {
    $d = $d->where('age','>',$age);
}    
$d = $d->paginate(20);

Upvotes: 0

Related Questions