Reusable Livewire computed properties

Reusable Livewire computed properties

You can use traits to add reusable computed properties to quickly access common data.

For example, we can create an HasUser trait, this allows you to access the current authenticated user from any Livewire component that uses this trait.

1<?php
2 
3namespace App\Traits;
4 
5use Livewire\Attributes\Computed;
6use App\Models\User;
7 
8trait HasUser {
9 
10 #[Computed]
11 public function user(): ?User
12 {
13 return auth()->user();
14 }
15 
16}

Let's take the following component and add our HasUser trait.

1namespace App\Livewire;
2 
3use Livewire\Component;
4use App\Traits\HasUser;
5 
6class Example extends Component
7{
8 use HasUser;
9}

Now we can access our user anywhere in our component class but also our Blade view:

1namespace App\Livewire;
2 
3use Livewire\Component;
4use App\Traits\HasUser;
5 
6class Example extends Component
7{
8 use HasUser;
9 
10 public function mount()
11 {
12 dd($this->user);
13 }
14}

Try it yourself in this interactive Wirebox.

To navigate
Press Enter to select