0

I have the following PHP code:

$users = DB::table('users');

if (Input::has('minAge') && Input::has('maxAge')) {
    $users = $users->whereBetween('age', array(Input::get('minAge'), Input::get('maxAge')));
} else if (Input::has('minAge')) {
    $users = $users->where('age', '>=', Input::get('minAge'));
} else if (Input::has('maxAge')) {
    $users = $users->where('age', '>=', Input::get('maxAge'));
}

if (Input::has('sex') && Input::get('sex') !== "0") {
    $users = $users->where('sex', '=', Input::get('sex'));
}

$users = $users->paginate(15);

return View::make('search.result', compact('users'));

However I would like to retrieve through Eloquent as the entity object has some functionality needed in view.

Anyway, I've tried to mimic the above but it doesn't work, I think the objects are rather overriden than chained.

Here is my attempt:

if (Input::has('minAge') && Input::has('maxAge')) {
            $users = User::whereBetween('age', array(Input::get('minAge'), Input::get('maxAge')));

} else if (Input::has('minAge')) {
            $users = User::where('age', '>=', Input::get('minAge'));

} else if (Input::has('maxAge')) {
            $users = User::where('age', '>=', Input::get('maxAge'));
}

if (Input::has('sex') && Input::get('sex') !== "0") {
            $users = User::where('sex', '=', Input::get('sex'));
}

$users = User::paginate(15);

return View::make('search.result', compact('users'));

1 Answer 1

1

Try

$input = Input::only('minAge', 'maxAge', 'sex');

$query = User::query();

if (! is_null($input['minAge'])) {
    $query->where('age', '>=', $input['minAge']);
}

if (! is_null($input['maxAge'])) {
    $query->where('age', '<=', $input['maxAge']);
}

if (! is_null($input['sex'])) && $input['sex'] !== "0") {
    $query->where('sex', '=', $input['sex']);
}

$users = $query->paginate(15);

return View::make('search.result', compact('users'));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.