I have created new component using php artisan make:component Test
.
Now, when creating that component, if I try to pass one word variable everything works fine (<x-test :testID="'test'"
). But when I try passing it as multi word, separating words by using underscore (<x-test :test_id="'test'"
), I am facing next error:
Unresolvable dependency resolving [Parameter #0 [ <required> $test_id ]] in class App\View\Components\Test
And that class looks like this:
class Test extends Component
{
public $test_id;
public function __construct($test_id)
{
$this->test_id = $test_id;
}
public function render()
{
return view('components.test');
}
}
Is this normal behaviour and is it even allowed to use underscore when creating variables inside components?
Livewire components do not support the classical __construct
constructor. Instead you better use the mount()
method.
Furthermore you should work with public properties like this
public $test_id;
public function mount()
{
// properly initialize the var
$this->test_id = 0;
}
and reference (see Data Binding) it in your view with
<x-test wire.model="test_id"/>
I generally would always go for camelCase
naming, f. ex. testId
. This is definately fully supported in Livewire (see docs).
Some general hint about naming variables
What you describe with one word and multi word variable is named
Update for comment component
class Comments extends Component
{
public int $postId;
public function mount()
{
$this->postId = 0;
}
public function render()
{
$comments = Comments::where('post_id', $this->postId)->get();
return view('post.list', [
'comments' => $comments,
]);
}
}
In your views you can use something like this.
<x-comments :postId="$post->id"/>
You don't need to inject it into the mount
method. Just use the public property.