简体   繁体   中英

How to send data from Livewire component to a controller?

I have a very basic Livewire component. I know, there is a wire:click , but I simplified it very much, to give you something by hand. In my real app, there is a calendar component and when you click on an event, it fires the emit() and sends data from the ui to the Livewire component, where it get's modified.

My question is: How can post this data from the Livewire component to the foo.store route?

app/Http/Livewire/Foo.php:

class Foo extends Component
{
    public $foo;

    protected $listeners = [
         'store' => 'store'
    ];

    public function render()
    {
         return view('livewire.foo');
    }

    public function store($data)
    {
         $payload = $this->do_complex_math_on_data($data);
         // ❓ post payload to FooController's store() function - HOW?
    }

    private function do_complex_math_on_data($data)
    {
         return 1+1;
    }
}

resources/views/livewire/foo.blade.php:

<div>
   <button>Click me!</button>
</div>

<script>
    document.addEventListener('livewire:load', function() {
        document.querySelector('button').addEventListener('click' () => {
            Livewire.emit('store', data.coming.from.ui);
        });    
    });
</script>

From your prospect of the controller, as Peppermintology stated, there are two types of controller, one is a standard Laravel controller and the second is a Livewire component controller, from there you have to understand that the livewire controller lifecycle is detached from Laravel. it is working as a waterfall, you can inject data from the Laravel controller to the Livewire component but from Livewire to Laravel standard component you can't, though you can pass data between the livewire ecosystem like from parent component to child or vice-versa

Like below

$this->emitUp('postAdded');

or

<button wire:click="$emitUp('postAdded')">

you can read more about nesting components in livewire Nesting component , and also about event Events

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM