I am creating a checkbox component in Laravel 9 and trying to access the isChecked method from component class as follows:
// app\View\Components\form-checkbox.php
namespace App\View\Components;
use Illuminate\View\Component;
class formcheckbox extends Component
{
public $name;
public $value;
public $actualValue;
/**
* Create a new component instance.
* @return void
*/
public function __construct($name, $value, $actualValue)
{
//
$this->name = $name;
$this->value = $value;
$this->actualValue = $actualValue;
}
public function isChecked($option)
{
return $option === $this->actualValue;
}
/**
* Get the view / contents that represent the component.
* @return \Illuminate\Contracts\View\View|\Closure|string
*/
public function render()
{
return view('components.form-checkbox');
}
}
<!-- resources\views\components\form-checkbox.blade.php -->
<div class="checkbox">
<label>
<input
type="checkbox"
name="{{ $name }}"
value="{{ $value }}"
actualValue={{ $actualValue }}
{{ $isSelected($value) ? 'checked="checked"' : '' }}>
{{ $slot }}
</label>
</div>
When I try to render the component:
<?php $val = 'Y'; ?>
<x-form-checkbox name="testChkBx[]" value="Y" actualValue="{{ $val }}"> Y </x-form-checkbox>
<x-form-checkbox name="testChkBx[]" value="YY" actualValue="{{ $val }}"> YY </x-form-checkbox>
It gives error:
Undefined variable $isSelected.
I found one similar issue but could not find how to call the isSelected method. I am trying this with a fresh Laravel installation.
class form-checkboxhuh I never knew you could do that! Might want to turn errors on.