То, что я хотел бы сделать, это построить объект по ходу поиска по фильтрам.
То, что вы делаете в настоящее время, - это применение фильтра и его внезапное завершение для каждого.
Сначала примените каждый присутствующий фильтр, а затем в конце выполните поиск.
Сделай так:
add filter (age).
add filter (nationality).
-> then finally execute search.
Не
filter (age) -> search. execute.
filter (nationality) -> search. execute.
Вот идея (конечно, это не проверено):
<?php
// $penpals = $this->penpalModel->getUsers()->latest()->paginate(12);
// base penpals object
$penpals = $this->penpalModel;
// start out with the initial original object, untouched
// if nickname is present, add filter nickname
if (!empty($request->name)) {
$users = $this->userModel->where('name', 'like', '%' . $request->name . '%')->get();
if (!empty($users)) {
// apply | attached user ids found
$penpals->whereIn('user_id', $users);
}
}
// dont cut off the query and execute yet, continually check other filters
if (!empty($request->gender) && $request->gender !== 'all') {
$penpals->leftJoin('users', 'penpals.user_id', '=', 'users.id')
->select('penpals.*', 'users.gender')
->where('users.gender', $request->gender);
}
// again, continue to the next set of filters (country search)
// and so on, the same syntax, build off of the base object and continually connect filters
// then on the end, EXECUTE it!
$penpalsData = $penpals->orderBy('penpals.created_at','desc')->paginate(12); // execute then builder after several layers of filters are applied!
$penpalsCount = count($penpalsData);
return view('penpal.index')->with([
'penpals' => $penpalsData,
'penpalsCount' => $penpalsCount
]);
Просто следуйте этой идее или концепции, это не ваша копия, а тип работы. Измените его и правильно подогнать под вашу бизнес-логику.