Traits

PHP Traits are a great way to re-use functionality between multiple Livewire components.

For example, you might have multiple "data table" components in your application that all share the same logic surrounding sorting.

Rather than duplicating the following sorting boilerplate in every component:

            
1class ShowPosts extends Component
2{
3 public $sortBy = '';
4 public $sortDirection = 'asc';
5 
6 public function sortBy($field)
7 {
8 $this->sortDirection = $this->sortBy === $field
9 ? $this->reverseSort()
10 : 'asc';
11 
12 $this->sortBy = $field;
13 }
14 
15 public function reverseSort()
16 {
17 return $this->sortDirection === 'asc'
18 ? 'desc'
19 : 'asc';
20 }
21 
22 ...
23}

You could instead extract this behavior into a re-usable trait called WithSorting:

            
1class ShowPosts extends Component
2{
3 use WithSorting;
4 
5 ...
6}
            
1trait WithSorting
2{
3 public $sortBy = '';
4 public $sortDirection = 'asc';
5 
6 public function sortBy($field)
7 {
8 $this->sortDirection = $this->sortBy === $field
9 ? $this->reverseSort()
10 : 'asc';
11 
12 $this->sortBy = $field;
13 }
14 
15 public function reverseSort()
16 {
17 return $this->sortDirection === 'asc'
18 ? 'desc'
19 : 'asc';
20 }
21}

Additionally, if you want to use Livewire's lifecycle hooks inside your traits but still be able to use them inside your component, Livewire offers a syntax that allows you to do this:

            
1trait WithSorting
2{
3 ...
4 
5 public function bootWithSorting()
6 {
7 //
8 }
9 
10 public function bootedWithSorting()
11 {
12 //
13 }
14 
15 public function mountWithSorting()
16 {
17 //
18 }
19 
20 public function updatingWithSorting($name, $value)
21 {
22 //
23 }
24 
25 public function updatedWithSorting($name, $value)
26 {
27 //
28 }
29 
30 public function hydrateWithSorting()
31 {
32 //
33 }
34 
35 public function dehydrateWithSorting()
36 {
37 //
38 }
39 
40 public function renderingWithSorting()
41 {
42 //
43 }
44 
45 public function renderedWithSorting($view)
46 {
47 //
48 }
49}

Livewire offers hooks for query strings as well.

            
1trait WithSorting
2{
3 ...
4 
5 protected $queryStringWithSorting = [
6 'sortBy' => ['except' => 'id'],
7 'sortDirection' => ['except' => 'asc'],
8 ];
9 
10 // or as a method
11 
12 public function queryStringWithSorting()
13 {
14 return [
15 'sortBy' => ['except' => 'id'],
16 'sortDirection' => ['except' => $this->defaultSortDirection()],
17 ];
18 }
19}

Note that you are allowed to override any query string in your component class.

← Previous Topic

Flash Messages

Next Topic →

Loading States