2

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>
4
  • you get only 1 record (array 2) with Location::whereIn('id',[05046,05005,05030])->get(); ? Commented Jun 25, 2021 at 3:36
  • Location::whereIn('id',[05046,05005,05030])->get(); with this can show all, but when use $val, it only show 1 id Commented Jun 25, 2021 at 3:39
  • Let me know, you got the same result with these 2 query? Location::whereIn('id',[05046,05005,05030])->get(); and Location::whereIn('id',["05046","05005","05030"])->get(); Commented Jun 25, 2021 at 3:44
  • ah sorry, in my example, forgot to add quote (') and i use this my code actually, Location::whereIn('id',["05046","05005","05030"]) with quote Commented Jun 25, 2021 at 3:47

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.