skip to Main Content

hello I’m new to livewire, I created a component for the radio buttons and I’m trying to show the selected radio value on the component view but its always giving null no matter what is the checked radio its always null

The Component View

@foreach ($brands as $brand)
<div class="template-checkbo">
    <input wire:model="brandsVal" name="brandsVal" type="radio" value="{{ $brand->id }}">
    <label class="main-label">
        {{ $brand->name }}
    </label>
</div>
@endforeach

@dump($brandsVal)

The Component Class

<?php

namespace AppHttpLivewire;

use LivewireComponent;

class BrandSidebar extends Component
{
   public $brands;
   public $brandsVal;

   public function render()
   {  
       return view('livewire.brand-sidebar');
   }
}

2

Answers


  1. Chosen as BEST ANSWER

    I found the solution after opening the console and seeing a Warning not an error

    Livewire: Multiple root elements detected. This is not supported.
    

    Apparently The view component must have one root element other wise the whole functionality wont work according to this doc:
    https://laravel-livewire.com/docs/2.x/troubleshooting#root-element-issues


  2. I think the issue is with this here
    wire:model="brandsVal"
    The issue with the current implementation is that all of the radio buttons have the same name attribute "brandsVal" and the same wire:model value "brandsVal", so when one of the buttons is selected, all of the buttons will have the same value.

    in your component class,
    try this instead

    //from  public $brandsVal;
    
    public $brandsVal = []; //sets the brandsVal property to an array. 
    

    Now generate the input elements in your blade file like this

    @foreach ($brands as $brand)
    <div class="template-checkbo">
        <input wire:model="brandsVal.{{ $brand->id }}" type="radio" value="{{ $brand->id }}">
        <label class="main-label">
            {{ $brand->id }}
        </label>
    </div>
    @endforeach
    

    Secondly, are you passing anything here? public $brands;

    Lastly, make sure to wrap your livewire blade file into just one html element.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search