Hello,
I'm building search for my worker table with eloqent, and for example I have two fields : $first_name = Input::get('first_name'); $city = Input::get('city');
I need, if $first_name is empty than find all workers from $city, and if $city is empty find all workers with $first_name, and if $first_name AND $city are not empty, than find all workers from that $city WITH that $first_name:
Problem was, if $fist_name is empty, it passes empty string "" and it look in DB for $fist_name = "" and it gets wrong result, I needed if $fist_name is empty don't pass it to query at all.
After few tries I came to this:
$workers = Worker::where(function($q) {
foreach(Input::all() as $key => $value) {
if ( $value != "" ) {
$q->where($key , $value);
}
}
})->get();
And as I test it it works fine, but my question is, is this good approach? Is there better way to do this? How would you do search with multiple WHERE but if Input is empty not to search for it?
My approach :
$name = Input::get('name', null);
$city = Input::get('city', null);
$query = Worker::select('fields', 'you', 'need');
// Add name filter
$query = is_null($name) ? $query : $query->whereName($name);
// Add city filter
$query = is_null($city) ? $query : $query->whereCity($city);
$workers = $query->get();
is_null
also saves from empty string ''
I would consider iterating through Input::all()
as not very wise .
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community