Gelbcke
Gelbcke

Reputation: 11

Laravel 5.8 - Get values from pluck result

I need help to make this code work. After make a search by a Software, my controller return the locals who have the software installed, and the S.O. who has the same. For example, this query will return "1 2", because this two images has "Google Chrome".

$img_id = Software::where('application', $request->input('application'))->pluck('imagem_id');

And than, I need to list all the locals who have this image, after consequence of the search by the Software.

$ambientes = Ambiente::where('imagem_id', $img_id)->get();

But she only show me the locals who have the imagem_id = 1, even I using a foreach in view:

@foreach ($ambientes as $value)
<tr>
   <td>{{ $value->unidade->name }}</td>
   <td>{{ $value->bloco->name }}</td>
   <td>{{ $value->name }}</td>
   <td>{{ $value->imagem_id }}</td>
</tr>
@endforeach

What I need to do to show every locals who has the image_id = 1 and 2??

Upvotes: 0

Views: 979

Answers (2)

Tim Lewis
Tim Lewis

Reputation: 29278

When you're trying to get records that match multiple IDs, you can't use where(), you'll need to use whereIn():

 $img_id = Software::where('application', $request->input('application'))->pluck('imagem_id');
 // This should return an array/Collection of `imagem_id` values.

 $ambientes = Ambiente::whereIn('imagem_id', $img_id)->get();

Now, $ambientes should contain Ambiente records that match all the imagem_id values returned from your initial query.

Upvotes: 2

nakov
nakov

Reputation: 14268

As you said, this

$img_id = Software::where('application', $request->input('application'))->pluck('imagem_id');

should return an array of the two ids like this:

[1, 2]

If that's the response then you can use whereIn:

$ambientes = Ambiente::whereIn('imagem_id', $img_id)->get();

This will give you a collection of both ambients, and the view stays the same.

Upvotes: 4

Related Questions