Understanding Laravel Livewire Components, Example!

Here, I want to show you something that I found very illustrative, so you understand exactly how components work in Livewire and why it's truly a SPA (Single Page Application). This means it doesn't reload the entire page, but only the part that's changing, that is, the component you're working with. At least, of course, in a basic way.

If you use the listener system to communicate with your father, grandfather, great-grandfather, aunt, or whoever, things obviously change. But I'm referring to the normal flow, so to speak.

We have a language selector. Notice that if I change it to "Spanish," everything appears in Spanish:

<?php

namespace App\Livewire\User;

use Livewire\Attributes\Layout;
use Livewire\Component;

use Illuminate\Support\Facades\App;

#[Layout('layouts.web')]
class UserProfile extends Component
{

    public $language;

    public function render()
    {
        if (!isset($this->language)) {
            // al cargar el componente, este codigo se ejecuta al language NO estar seleccionado 
            // por el usuario
            $this->language = session('locale') ?? App::getLocale();
        } else {
            // se ejecuta desde la vista asociada por el .live
            session(['locale' => $this->language]);
            App::setLocale($this->language);
        }
        
        return view('livewire.user.user-profile');
    }
}

And the view:

<div class="max-w-md m-auto mycard">
    <div class="grid grid-cols-1 gap-2 my-3 mycard-body">
        <flux:input :label="__('Email')" value="{{ auth()->user()->email }}" disabled readonly/>

        <flux:input :label="__('Name')" value="{{ auth()->user()->name }}" disabled readonly />

        <flux:select :label="__('Language')" id="language" wire:model.live="language" x-data @change="setTimeout(function(){window.location.reload()}, 100)" class="mt-1 block w-full rounded border-gray-300">
            <option value="es">Español</option>
            <option value="en">English</option>
        </flux:select>

    </div>
</div>

Which is consumed through a route; additionally, as you can see, the component uses a template called web.blade.php that has menus with text to be translated.

What the previous component does is set a new language in the application. When changing the select with .live, it causes ONLY the component to redraw. If you check the Network, you'll see that a single request is made to the server when changing the SELECT. This is achieved using wire:model.live, a very useful feature if used intelligently (please don't include it in every text field because you'll overload the server!).

In this case, it makes sense for elements like selects, where I want a language change to be applied in real time.

What actually happens when you change the language?

When you change the language, a method is executed on the server (in Laravel, using App::setLocale()), and we pass it the new language. In this example, I use [es] for Spanish and [es] for English. I've already set all the translations from the start of the project, so they apply immediately.

The key point here is that it ONLY reloads the component, not the entire page. You can easily notice this because when you change the language, the header (part of the layout) doesn't change, but the component's content does.

Why is this behavior important?

This is precisely what happens in a SPA: only the part that's really needed is refreshed. If I wanted the entire page to reload, I could issue an event to the parent component (or even the layout), but in this case I didn't because it wasn't necessary. I also don't think the user is switching languages ​​every five seconds.

I agree to receive announcements of interest about this Blog.

I show an example of how Livewire components work, which is what it reloads when re-rendering.

- Andrés Cruz

En español