Sometimes such a scene when we use where in Laravel
, like this:
if (!empty($request->input('user_name'))) {
$where[] = ['user_name', 'like', "%" . $request->input('user_name') . "%"];
}
if (!empty($request->input('group_id'))) {
$where[] = ['group_id', $request->input('group_id') ];
}
if (!empty($request->input('email'))) {
$where[] = ['email', 'like', "%" . $request->input('email') . "%"];
}
if (!empty($request->input('mobile'))) {
$where[] = ['mobile', 'like', "%" . $request->input('mobile') . "%"];
}
$users = User::where($where)->get();
but its so ugly, but I just want use the this User::search($request->only(['user_name', 'email', 'mobile']));
, maybe we have to design some rules for the key name of the input name and do you have some good idea for this condition? Thanks.
You can create local scope:
public function scopeSearch($q, $inputs)
{
$where = [];
foreach ($inputs as $key => $data) {
$where[] = [$key, 'like', "%".$data."%"];
}
return $q->where($where);
}
And then use it:
User::search($request->only(['user_name', 'email', 'mobile']))->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With