Skip to content

Instantly share code, notes, and snippets.

@tuanpht
Created November 12, 2020 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuanpht/87ab93aadc85b147b4d907a4af0980ac to your computer and use it in GitHub Desktop.
Save tuanpht/87ab93aadc85b147b4d907a4af0980ac to your computer and use it in GitHub Desktop.
Laravel searchable field

Simple

$searchable = [
    'type',
    'date',
];

$petsQuery = Pet::where('user_id', '=', $request->user()->id);
// OR: $petsQuery = Pet::query(). For empty query

foreach ($searchable as $field) {
    $filterValue = $request->query($field);
    if ($filterValue) {
        $petsQuery->where($field, '=', $filterValue);
    }
}

$pets = $petsQuery->get(); // OR: pagination

Or if you request field different from database field, you can use key-value array:

$searchable = [
    'type' => 'type',
    'date' => 'created_at',
];

More advanced

Using callback

$searchable = [
    'type' => function ($query, $value) {
        $query->where('type', '=', $value);
    },
    'date' => function ($query, $value) {
        $query->whereRaw('DATE(created_at) = ?', $value);
    },
];

$petsQuery = Pet::where('user_id', '=', $request->user()->id);

foreach ($searchable as $field => $callback) {
    $filterValue = $request->query($field);
    if ($filterValue) {
        $callback($petsQuery, $filterValue);
        // OR use: call_user_func($callback, $petsQuery, $filterValue);
    }
}

$pets = $petsQuery->get(); // OR: pagination

This is just idea, apply it on your own way for each project requirement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment