You need return after the last if statement in the scopeOfAgeRange method. Just return the $query variable.
return $query;
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
can anyone help for check the logic of scopeOfAgeRange is correct, Thx
Controller
class SearchStaff extends Controller
{
public function __invoke(Request $request)
{
$staffs = Staff::ofFilter($request)->get();
return view('staffs.index', compact('staffs'));
}
}
Model
class Staff extends Model
{
public function scopeOfFilter($query, $request)
{
return $query->ofGender($request->gender)
->ofAgeRange($request->from_age, $request->to_age);
}
public function scopeOfGender($query, $gender = null)
{
if ($gender === '0' || $gender === '1') {
return $query->where('gender', $gender);
}
}
public function scopeOfAgeRange($query, $fromAge = null, $toAge = null)
{
$fromAge = is_string($fromAge) ? intval($fromAge) : 0;
$toAge = is_string($toAge) ? intval($toAge) : 0;
$minAge = min([$fromAge, $toAge]);
$maxAge = max([$fromAge, $toAge]);
if ($minAge === 0) {
$minAge = $maxAge;
}
if ($minAge > 0 && $maxAge > 0) {
return $query->whereBetween('birth_date', [
// small value eg. 1970-04-03
now()->subYears($maxAge + 1)->format('Y-m-d'),
// large value eg. 1980-04-03
now()->subYears($minAge)->format('Y-m-d'),
]);
}
}
}
scopeOfAgeRange possible combination
$fromAge | $toAge |
---------------------------------
0 | 0 | Pass - no query
35 | 29 | Pass - query between 35+1,29
29 | 35 | Pass - query between 35+1,29
0 | 35 | Pass - query between 35+1,35
35 | 0 | Pass - query between 35+1,35
Please or to participate in this conversation.