Home > Back-end >  Laravel, can't build query for array in multiple <select>
Laravel, can't build query for array in multiple <select>

Time:02-28

I made a filter to find businesses

There are several cities to choose from

enter image description here

Cities store on city_id column

The filter looks like this

<select id="city" multiple name="city[]">
  @foreach($cities as $city)
    <option value="{{ $city->name }}">{{ $city->name }}</option>
  @endforeach
</select>

All request

dd($request->all()) 

shows me this

enter image description here

I build query for franchise or business like this

if ($request->has('fb')) {
  $businessesQuery->where('fb', $request->fb);
}

I try to build query like this but it's not works

if ($request->has('city[]')) {
    $typeArray = explode(",", $request->city[]);
    $businessesQuery->whereIn('city_id', $typeArray);
}

Help me solve this issue, I would be very grateful!

CodePudding user response:

Your html must use city_id as a value and not the city name. Because you're trying to search using the id not name.

    <option value="{{ $city->id }}">{{ $city->name }}</option>

explode function takes a string as in input and returns an array. In your case your city[] request value is already an array visible from the dump. You should use it directly. Something like this.

if ($request->has('city')) {
    $businessesQuery->whereIn('city_id', $request->input('city');
}
  • Related