user2682025
user2682025

Reputation: 804

Laravel variable increments value in a foreach loop

I'm having a weird issue, I have two foreach loops inside blade. when I use the id value of the model received from the first foreach loop and use it inside the second foreach loop the value increments suddenly.

Livewire component:

class HomePage extends Component
{
    public $subjectComments = [];
    public function loadSubjectComments($type, $id)
        {
            $article = Article::findOrfail($id);
            $this->subjectComments[$article->id] = $article->comments;
        }
}

in the blade:

    @foreach($activities as $activity)
        <a wire:click="loadSubjectComments('{{$activity->subject_type}}', {{ $activity->subject->id }})" @click="showCommentTextBox{{ $activity->subject->id }} = ! showCommentTextBox{{ $activity->subject->id }}" class="cursor-pointer">
            <div class="flex flex-row pr-2 justify-center text-center items-center">
                <div>{{$activity->subject->comments->count()}}</div>
            </div>
        </a>
        {{$activity->subject->id}} //at this level the value is correct
        @if($subjectComments)
            @foreach($subjectComments[$activity->subject->id] as $index => $comment) //here the value of $activity->subject->id increments by 1
            @endforeach
        @endif
    @endforeach

it gives this error "Undefined array key 6" where the id actually is 5 when reading from {{$activity->subject->id}}

Upvotes: 0

Views: 539

Answers (1)

Qirel
Qirel

Reputation: 26490

So a few things here,

  1. It's not given that the $subjectComments variable holds any data for that activity, since the check for @if($subjectComments) only checks that there is at least one comment for any activity, not just the one you are iterating. You can fix this by using the null coalescing operator in your loop.

  2. When using lops in Livewire with dynamic content, you should be using wire:key and only have one root element in your loop.

@foreach($activities as $activity)
    <div wire:key="activity-{{ $activity->id }}">
        <a wire:click="loadSubjectComments('{{ $activity->subject_type }}', {{ $activity->subject->id }})" 
           @click="showCommentTextBox{{ $activity->subject->id }} = ! showCommentTextBox{{ $activity->subject->id }}" 
           class="cursor-pointer"
        >
            <div class="flex flex-row pr-2 justify-center text-center items-center">
                <div>{{ $activity->subject->comments->count() }}</div>
            </div>
        </a>
        {{ $activity->subject->id }}
        @if($subjectComments)   
            @foreach($subjectComments[$activity->subject->id] ?? [] as $index => $comment) 
                <div wire:key="comment-{{ $comment->id }}">
                </div> 
            @endforeach
        @endif
    </div>
@endforeach

Upvotes: 0

Related Questions