I have a query
$BaseUsers = DB::table('users', 'users.ustatus', '=', '1')
->join('user_infos', 'user_infos.user_id', '=', 'users.id')
->select('users.*', 'user_infos.add1', 'user_infos.add3')
->paginate(3);
It work fine. But i need insert condition "where" to search in result i send $request from form. How insert condition to query?
In PHP it looks like this:
if($request['add_1'])
{
$insert1=" and add_1<>'' ";
}
if($request['add_2'])
{
$insert2=" and add_2<>'' ";
}
...
$sql=" SELECT users.*, user_infos.add1, user_infos.add3 FROM users JOIN user_infos where users.ustatus=1 and user_infos.user_id=users.id ".$insert1." ".$insert2."";
How can this be done on laravel in Controller? I mean - just insert the necessary condition insert1, insert2 ... into the query
CodePudding user response:
you can use where()
and has()
to build your query
$query = DB::table('users');
if($request->has('age')) {
$query->where('age', '>', $request->age);
}
$query = $query->get();
I hope it's helpful
CodePudding user response:
All is simple ) I use when in query
$BaseUsers = DB::table('users', 'users.ustatus', '=', '1')
->join('user_infos', 'user_infos.user_id', '=', 'users.id')
->when($request->input('f_add3'), function ($query) {
return $query->where('user_infos.add3', '<>', '');
})
->select('users.*', 'user_infos.add1', 'user_infos.add3')
->paginate(3);