itnet
itnet

Reputation: 71

How to use where in when value is array in laravel?

I have an array like this

array:3 [▼
  0 => "05046"
  1 => "05005"
  2 => "05030"
]

and i want to show the location based on their id in array above (the id is 05046,05005,05030. how to applied it in my controller below?

actually I want to query something like this using where in. when the id i put manual, it works.

$location= Location::whereIn('id',['05046','05005','05030'])->get();

But, since the id that i get is in array, how to apply it in controller?

$location= Location::whereIn('id',[$val])->get();

i try this with $val but in select option in the blade, the location only show the latest id (array no 2) $val when dd($val) will show

array:3 [▼
  0 => "05046"
  1 => "05005"
  2 => "05030"
]

the blade

<select class="select" name="loc" id="loc" required="">
     @foreach ($location as $loc)
            <option value="{{$loc->id}}">{{$loc->name}}</option>
      @endforeach
</select>

Upvotes: 2

Views: 313

Answers (1)

max234435
max234435

Reputation: 567

Here is your mistake. If you already have the $val array:

$val = [
  0 => "05046"
  1 => "05005"
  2 => "05030"
];

dont add [] brackets when using it inside whereIn because then you are declaring that its an array inside an array. whereIn requires the second parameter to be a regular array. Simply do this:

$location= Location::whereIn('id', $val)->get();

Upvotes: 1

Related Questions