Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel, can't build query for array in multiple <select>

I made a filter to find businesses

There are several cities to choose from

enter image description here

Cities store on city_id column

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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');
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading