Search code examples
laravellaravel-livewire

Livewire & Laravel 8: updating global components


I’m fairly new to the components & livewire game so I’m getting very confusing when I need to update a component value from other sources. Let me explain:

I’m using a default Laravel 8 installation with Livewire - no JetStream.

My navigation file (the default one that comes with the installation) has 3 individual components containing: total of points achieved, total of lives and remaining lives.

Loads like:

<x-points>0</x-points>

<x-lifes>0</x-lifes>

<x-remaining-lifes>0</x-remainung-lifes>

My question: how do I update any of those components when I execute actions from different sources like:

  • user answer a question (file Answer.php)
  • User clicks on an action at the footer of my application (let’s call this Regenerate.php)
  • User request tips so I need to subtract (Tips.php)

Solution

  • I would change your three main blade components for livewire componentes:

    <livewire:points></livewire:points>
    
    <livewire:lifes></livewire:lifes>
    
    <livewire:remaining-lifes></livewire:remaining-lifes>
    
    

    So for example, let's create the points and answer components.

    // Points.php livewire component
    
    public int points = 0;
    
    public $listeners = ['loadUserPoints'];
    
    public function render() { ... }
    
    public function loadUserPoints()
    {
         $this->points = user()->points()->sum('total');
    }
    
    // points.blade.php livewire component
    
    <div wire:init="loadUserPoints">{{ $points }}</div>
    
    

    Now let's abstract the answer component.

    // answer livewire component (very abstracted)
    
    public function save()
    {
         user()->answers()->create($this->data);
    
         // this will be listened by the points component
         // that will run its query and update your frontend
         $this->emit('loadUserPoints');
    }
    
    

    So livewire works mainly for events, you have to use it to pass data cross multiple components. To update your frontend as an SPA you're not gonna use blade components, you have to use livewire component or a lot of javascript to handle the DOM.