stoneworld stoneworld - 17 days ago 8
PHP Question

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.

Answer

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();
Comments