skip to Main Content

I have already a livewire component which controller fetch data from database and second component is product in that component controller i’m fetching products data with pagination but it will give me this error
Livewire only supports one HTML element per component. Multiple root elements detected for component: [user-products]

Livewire component controller UserProducts:

class UserProducts extends Component
{
    use WithPagination;

    public function render()
    {
        return view('livewire.user-products', ['products' => Product::paginate(5)]);
    }
}

Livewire component view user-products:

@foreach ($products as $items)
    <div class="card" style="width: 18rem;">
        <img src="{{url('storage/products')}}/{{$items->image}}" class="card-img-top" alt="...">
        <div class="card-body">
            <h5 class="card-title">{{$items->title}}</h5>
            <p class="card-text">{{$items->description}}</p>
            <p class="text-success">${{$items->primary}}</p>
        </div>
    </div>
@endforeach

and include the compoent in products blade main file:

<div class="row">
            <div class="col-md-4">
                @livewire('user-products')
            </div>
        </div>

What i want to say is how can i fixed this issue…

2

Answers


  1. In Livewire everything needs to be in one parent element, so your user-products blade file should look like this:

    <div>
    @foreach ($products as $items)
        <div class="card">
        </div>
    @endforeach
    </div>
    
    Login or Signup to reply.
  2. Don’t forget to add a wire:key to any iterable, or Livewire won’t be able to easily track it.
    It’s also good to get into the habit of using forelse and empty in case you do pass an empty array.

    <div>
        @forelse ($products as $productIndex => $productItem)
            <div class="card" wire:key="products-{{ $productIndex }}">
                   
            </div>
        @empty
            No Products
        @endforelse
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search