pmiranda
pmiranda

Reputation: 8470

Laravel, check if value is in some collection (in blade)

I have 2 collections, $all have all the values (5), and $some has only 2 values. I'm trying to this: For each value of $all, if that item in the loop is in the $some collection, put the the value of that $some item (something like that) in the input:

@foreach($all as $item)
    <div>
        @if(in_array($item->id, $some))
            <input type="number" value="{{ Here I need to put the value of $some where id of some be teh same of $all }}">
        @else
            <input type="number" value="0">
        @endif
    </div>
@endforeach

I don't know how to read and decide all that inside the blade.

EDIT: I was trying something like this:

@if(in_array($item->id, $some))
    <input type="number"  value="{{ $some->find($item->id)->value }}">

Upvotes: 1

Views: 4022

Answers (2)

Ax3
Ax3

Reputation: 21

In my case, i was trying to do this on a array of checkboxes input, in case someone needs it this way:

<input type="checkbox" name="guides[]" value="{{ $item->id }}"
    {{ in_array($item->id, $some->pluck('id')->toArray()) ? 'checked' : '' }} >

Upvotes: 1

Watercayman
Watercayman

Reputation: 8178

I don't know what the specific fields are on $some, but you can do what you want (replacing the fields you need to compare or show) like this:

@if(in_array($item->id, $some->pluck('id')->toArray()))
    <input type="number" value="{{ $some->where('id', $item->id)->first()->fieldYouWant}}">
@else
    <input type="number" value="0">
@endif

Basically, pull the $some ids into an array, compare the current looped $item->id (from $all), and if it hits, pull the specific $some object that matched (id from $some, and id from current $all item) and get the value you need from whatever the field you need is called.

Upvotes: 5

Related Questions