Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simplify multi search in Laravel?

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.

like image 431
LaravelFly Avatar asked Mar 10 '23 16:03

LaravelFly


1 Answers

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();
like image 151
Alexey Mezenin Avatar answered Mar 16 '23 03:03

Alexey Mezenin