Search code examples
phplaravellaravel-blade

duplicate data in blade laravel


i´m trying automate information in my blade. I have a contract, this contract have one or more installable items. i´m doing a foreach and generate h6 with name and cuantity.

In my db only have one item:

enter image description here

if i do dd() from $itemsInstallation->item return this item information:

enter image description here

but when i do my foreach to create h6 with information, all data it´s duplicated:

enter image description here

Contract, have relation with itemsContract, and itemsContract have a relation with items. I´m getting ok item information, but i don´t know why my data it´s duplicated. To create foreach, i´m doing:

@foreach ($itemsInstallation as $item)
   <h6>{{ $itemsInstallation->item->name }} -- {{ $itemsInstallation->cuantity }} uds</h6>
@endforeach

Anybody, can say me that i´m doing bad? thanks for readme and sorry for my bad english.

I resolve my problem

reviewing all my logic, i can show that my relationship was wrong, i has a hasOne instead of hasMany. Now my foreach, it´s a simple for:

@for ($i = 0; $i < count($itemsInstallation->item); $i++)
    <h6>{{ $itemsInstallation->item[$i]->name }} -- {{ $itemsInstallation->item[$i]->cuantity }} uds</h6>
@endfor

Solution

  • You're using foreach loop but instead of calling item you're calling array.

    It should be like that:

    @foreach ($itemsInstallation as $item)
       <h6>{{ $item->name }} -- {{ $item->cuantity }} uds</h6>
    @endforeach
    

    You can use Forelse which has empty condition, saves you from error when there will be no data.

    @forelse ($itemsInstallation as $item)
       <h6>{{ $item->name }} -- {{ $item->cuantity }} uds</h6>
    @empty
    @endforelse
    

    For more information visit: https://laravel.com/docs/10.x/blade#loops