Livewire is a full-stack framework for Laravel that makes building dynamic front-ends as simple as writing vanilla PHP. The last time I had a chance to work with it was in September and a lot has changed since then that makes it a lot easier to DRY up your components.

Computed Properties

If you've ever worked with Vue.js or Eloquent models than you'll be familiar with computed properties. Since 0.5.0 they are supported by following the get*Property naming convention for your functions that should represent computed properties.

Don't Repeat Yourself

The biggest annoyance for working with Livewire at the time was that you would have to either manually retrieve a model instance or implement some helper methods that you would need to call when you want to access the property. Now that computed properties exists I can clean up my components that work with specific types of models by implementing traits that remove all the boilerplate from my components.

<?php

namespace App\Http\Livewire\Concerns;

use App\User;

trait InteractsWithUser
{
    public ?int $userId = null;

    public function mount(User $user): void
    {
        $this->userId = $user->id;
    }

    public function getUserProperty(): User
    {
        return User::findOrFail($this->userId);
    }
}

Adding this trait to a component means that I'll have to include a component with @livewire('update-name', $user) so that the user ID can be set and later on in the component I can simply access $this->user to interact with the user model.

<?php

namespace App\Http\Livewire;

use App\User;
use Livewire\Component;

class UpdateName extends Component
{
    use Concerns\InteractsWithUser;

    public function doSomeThing(): void
    {
        dd($this->user);
    }
}

Conclusion

There is one thing that you'll have to keep in mind when using computed properties with Livewire. Depending on how much reactivity and real-time validation you perform in your component you should consider to implement model caching because you otherwise will end up bombarding your database with queries for data that hasn't changed since the last time you queried it. There are a few great packages for this but GeneaLabs/laravel-model-caching is the easiest and best from my personal experience.