A
A
Andre972021-07-16 16:02:46
Laravel
Andre97, 2021-07-16 16:02:46

How to make a request to the model for a selection of two fields, each of which is optional?

Good afternoon. The situation is something like this. There is a table of users. Users, among other things, have age and work experience. How to make a request through the model so that it selects them by age and experience? These options may or may not be available. If there is no parameter, then so that it returns everyone, and iterates over the other parameter. If two parameters are not present, it turns out it is necessary to return all.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2021-07-16
@Andre97

$query = User::query();

if ($request->has('age')) {
  $query->where('age', $request->get('age'));
}

if ($request->has('experience')) {
  $query->where('experience', $request->get('experience'));
}

$users = $query->get();

You can write using ->when(), but for my taste it only complicates the code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question