\$\begingroup\$
\$\endgroup\$
Brief:
I've create simple filter in my laravel project. I'll send parameters with ajax request.
Code:
public function specialitiesAjaxLoadMore(Request $request)
{
$city = null;
if(isset($request->city_id)) {
$city = City::find($request->city_id);
if($city !== null) {
$city = $city->id;
}
}
$sex = null;
if((isset($request->sex) && is_numeric($request->sex)) && $request->sex == 1 || $request->sex == 2) {
$sex = $request->sex;
}
$ageFrom = null;
if((isset($request->ageFrom) && is_numeric($request->ageFrom)) && $request->ageFrom > 7) {
$ageFrom = $request->ageFrom;
}
$ageTo = null;
if((isset($request->ageTo) && is_numeric($request->ageTo)) && $request->ageTo > 7) {
$ageTo = $request->ageTo;
}
if(isset($city)) {
$candidates = Candidate::where('city_id', $city)->get();
}
if(isset($sex)) {
$candidates = Candidate::where('sex', $sex)->get();
}
if(isset($ageFrom)) {
$candidates = Candidate::where('birthday', '<=', date('Y-m-d', strtotime("-$ageFrom years")))->get();
}
if(isset($ageTo)) {
$candidates = Candidate::where('birthday', '>=', date('Y-m-d', strtotime("-$ageTo years")))->get();
}
if(isset($city, $sex)) {
$candidates = Candidate::where('city_id', $city)->where('sex', $sex)->get();
}
if(isset($city, $sex, $ageFrom)) {
$candidates = Candidate::where('city_id', $city)
->where('sex', $sex)
->where('birthday', '<=', date('Y-m-d', strtotime("-$ageFrom years")))
->get();
}
if(isset($city, $sex, $ageFrom, $ageTo) && $ageTo < $ageFrom) {
$candidates = Candidate::where('city_id', $city)
->where('sex', $sex)
->where('birthday', '<=', date('Y-m-d', strtotime("-$ageFrom years")))
->where('birthday', '>=', date('Y-m-d', strtotime("-$ageTo years")))
->get();
}
}
In my case there will be a lot of parameters from the request and if I continue to write everything in such a way as seisai then there will be a lot of combinations. So is it possible to improve or shorten my current code?
asked Oct 29, 2018 at 9:24
1 Answer 1
\$\begingroup\$
\$\endgroup\$
https://laravel.com/docs/5.7/queries#where-clauses
$where = [];
if($city) {
$where[] = ['city_id', '=', $city];
}
if($sex) {
$where[] = ['sex', '=', $sex];
}
if($ageFrom) {
$where[] = ['birthday', '<=', date('Y-m-d', strtotime("-$ageFrom years"))];
}
if($ageTo) {
$where[] = ['birthday', '>=', date('Y-m-d', strtotime("-$ageTo years"))];
}
$candidates = Candidate::where($where)->get();
answered Oct 29, 2018 at 9:38
lang-php