laravel-livewire

How to pass and use parameters in volt class?


Reading https://livewire.laravel.com/docs/volt docs I want to use volt instead of piece of code :

<div>
    <div>
        <div class="w-4/12 pb-0 pl-2 md:pt-3">
            <label for="id">Id: </label>
        </div>
        <div class="p-2 w-full">
            <input
                id="id" name="id" type="text"
                value="{{ $form->id }}"
                tabindex="-1"
                readonly/>
        </div>
    </div>
</div>

So I created a class with command :

php artisan make:volt common/controls/readonlyInput --class

and try to fill file resources/views/livewire/common/controls/readonlyinput.blade.php with code :

<?php

use Livewire\Volt\Component;

use function Livewire\Volt\{mount, state};

state(['id'=> '', 'form'=> '']);


mount(function ($id, $form) { // ERROR POINTING AT THIS CLASS
    $this->id = $id;
    $this->form = $form;
});
new class extends Component {
    //
}; ?>

<div>
    <div>
        <div class="w-4/12 pb-0 pl-2 md:pt-3">
            <label for="{{ $id }}">Id: </label>
        </div>
        <div class="p-2 w-full">
            <input
                id="id" name="id" type="text"
                value="{{ $id }}"
                tabindex="-1"
                readonly/>
        </div>
    </div>
</div>

But I got error :

Undefined variable $id

when calling this class in blade file :

@livewire('common.controls.readonlyinput', ['id'=> 'id', 'form'=> $form])

$form - is livewire form I use in livewire for data saving

What is wrong in my code and which valid ?

"laravel/framework": "^11.9",
"livewire/livewire": "^3.5",
"livewire/volt": "^1.6",

Thanks in advance!


Solution

  • You messed up with Volt class and functional API. Your Livewire component should use one of this approaches, but not both at the same time.

    If you want pass parameters into volt components which use functional API, consider using state function without default value.

    <?php
    
    use function Livewire\Volt\state;
    
    state(['id']);
    
    ?>
    
    <section>
        {{ $id }}
    </section>
    

    Than use this directive to import child component into your parent view.

    <livewire:path.to.your.component.component-name :id="1"/>