mardi 3 septembre 2019

How to query with matching any values from fields in table using Laravel?

Say I have this table:

requests

id | first_name | last_name | facility | created_at
1  | John       | Doe       | 1        | 2019-08-22 15:24:24
2  | Mark       | Anderson  | 1        | 2019-08-30 14:38:28
3  | Arnold     | Roberts   | 2        | 2019-08-24 15:38:28

And in my UI, I have a search filter with match all and match any option.

Choosing match all will only return rows with all matching values from the variables. Looks like this:

$query = Request::query();

/* Will always be present */
if (Input::has('name')) {
  $query = $query->where('first_name', 'LIKE', '%'.Input::get('name').'%')->orWhere('last_name', 'LIKE', '%'.Input::get('name').'%');
}

/* Not required */
if (Input::has('start')) {
  $query = $query->whereBetween('created_at', [Input::get('start'), Input::get('end')]);
}

/* Not required */
if (Input::has('facility')) {
  $query = $query->where('facility', '=', Input::get('facility'));
}

$result = $query->get();

So in the code above, if one of the not required values is present and doesn't match any value in database, it'll return no results.

So what if I want to use the match any option?

/* Will always be present */
if (Input::has('name')) {
  $query = $query->where('first_name', 'LIKE', '%'.Input::get('name').'%')->orWhere('last_name', 'LIKE', '%'.Input::get('name').'%');
}

/* Not required but if present and no value in db, should still return value based on other query */
if (Input::has('start')) {
  $query = $query->whereBetween('created_at', [Input::get('start'), Input::get('end')]);
}

/* Not required but if present and no value in db, should still return value based on other query */
if (Input::has('facility')) {
  $query = $query->where('facility', '=', Input::get('facility'));
}

In the code above, the name is required and the other fields is not. So when the range date and facility doesn't match any in the table, it should still return a value. But if one of them or both of them matches values in the table, it should return those. Is it possible?

Any help would be much appreciated. Thank you.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2Lj0ala
via IFTTT

Aucun commentaire:

Enregistrer un commentaire