Answer the question
In order to leave comments, you need to log in
How to process the search form?
Good day. It is necessary to process the search form and issue values depending on the form parameters.
There is this form:
<form name="searchForm" id="searchForm" action="{{ route('search') }}" method="post">
{{ csrf_field() }}
<div class="form-group">
<input type="text" name="searchString" id="searchString" class="form-control" placeholder="Поиск..." autofocus>
</div>
<div class="form-group">
<label for="sex">Пол:</label>
<input type="checkbox" name="man" value="male" checked> Муж
<input type="checkbox" name="woman" value="female" checked> Жен
</div>
<div class="form-group">
<label for="age">Возраст:</label>
<input type="text" id="ageFrom" name="ageFrom" placeholder="С">
<input type="text" id="ageTo" name="ageTo" placeholder="По">
</div>
<div class="form-group">
<input type="submit" name="submitBtn" id="submitBtn" value="Поиск" class="btn btn-default">
</div>
</form>
public function search(Request $request)
{
// dd($request->man);
$users = User::where(function ($query) use ($request) {
$query->where('first_name', 'like', '%'.$request->searchString.'%')->
orWhere('last_name', 'like', '%'.$request->searchString.'%')->
orWhere('middle_name', 'like', '%'.$request->searchString.'%')->get();
})->where(function ($query) use ($request) {
if ($request->man && $request->woman) {
$query->where('sex', 'male')->where('sex', 'female');
} elseif ($request->man && !$request->woman) {
$query->where('sex', 'man');
} elseif (!$request->man && $request->woman) {
$query->where('sex', 'female');
} else {
$query->where('sex', null);
}
})->where(function ($query) use ($request) {
})->paginate(2);
return view('user.index')->withUsers($users);
}
Answer the question
In order to leave comments, you need to log in
First, replace this
if ($request->man && $request->woman) {
$query->where('sex', 'male')->where('sex', 'female');
} elseif ($request->man && !$request->woman) {
$query->where('sex', 'man');
} elseif (!$request->man && $request->woman) {
$query->where('sex', 'female');
} else {
$query->where('sex', null);
}
if ($request->man) {
$query->where('sex', 'man');
}
if ($request->woman) {
$query->where('sex', 'female');
}
You yourself have complicated everything, you just need to where
pass an array, checkboxes and that's it. For example:
$users = DB::table('users')->where([
// То есть сюда массив с тем, что там у вас в форме на выбирали при поиске и все.
['sex', 'man'],
['sex', 'female'],
])->get();
$users = DB::table('users')
// ['man', 'female'] Это массив с реквеста, тут может быть и null и man и сразу все вместе... и что вам нужно
->whereIn('sex', ['man', 'female'])
->get();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question