Better way to filtering data with query string #36503
-
Hello, I want to filter students list using query string. This is my current code: public function index(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => ['nullable', 'string', 'max:64'],
'code' => ['nullable', 'digits:10'],
'gender' => ['nullable', 'in:male,female'],
]);
if ($validator->fails()) {
return back()
->withErrors($validator)
->withInput();
}
$students = Student::orderByDesc('id');
if ($request->has('name')) {
$students = $students->where('full_name', 'LIKE', '%'.$request->name.'%');
}
if ($request->has('code')) {
$students = $students->where('national_code', $request->code);
}
if ($request->has('gender')) {
$students = $students->where('gender', $request->gender);
}
return view('admin.students', ['students' => $students->paginate()]);
} I want to know is there a better way to do this without if-else statements? |
Beta Was this translation helpful? Give feedback.
Answered by
brunogaspar
Mar 8, 2021
Replies: 1 comment
-
You can use the conditional clauses for this. $students = Student::query()
->orderByDesc('id')
->when($request->input('name'), function ($query, $name) {
return $query->where('full_name', 'LIKE', '%'.$name.'%');
})
->when($request->input('code'), function ($query, $code) {
return $query->where('national_code', $code);
})
->when($request->input('gender'), function ($query, $gender) {
return $query->where('gender', $gender);
}); |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
AmRo045
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use the conditional clauses for this.