Skip to content

Instantly share code, notes, and snippets.

@jvadillo
Created September 23, 2018 10:29
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 jvadillo/e08ae3d7e19bb562f288b52da7a004aa to your computer and use it in GitHub Desktop.
Save jvadillo/e08ae3d7e19bb562f288b52da7a004aa to your computer and use it in GitHub Desktop.
Handle search with filters in PHP with Laravel an Eloquent
public function filter(Request $request, User $user)
{
$user = $user->newQuery();
// Search for a user based on their name.
if ($request->has('name')) {
$user->where('name', $request->input('name'));
}
// Search for a user based on their company.
if ($request->has('company')) {
$user->where('company', $request->input('company'));
}
// Search for a user based on their city.
if ($request->has('city')) {
$user->where('city', $request->input('city'));
}
// Continue for all of the filters.
// Get the results and return them.
return $user->get();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment