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:

class ShowPosts extends Component
{
    public $sortBy = '';
    public $sortDirection = 'asc';

    public function sortBy($field)
    {
        $this->sortBy = $field;

        $this->sortDirection = $this->sortBy === $field
            ? $this->reverseSort();
            : 'asc';
    }

    public function reverseSort()
    {
        return $this->sortDirection === 'asc'
            ? 'desc'
            : 'asc';
    }

    ...
}

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

class ShowPosts extends Component
{
    use WithSorting;

    ...
}
trait WithSorting
{
    public $sortBy = '';
    public $sortDirection = 'asc';

    public function sortBy($field)
    {
        $this->sortBy = $field;

        $this->sortDirection = $this->sortBy === $field
            ? $this->reverseSort();
            : 'asc';
    }

    public function reverseSort()
    {
        return $this->sortDirection === 'asc'
            ? 'desc'
            : 'asc';
    }
}

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:

trait WithSorting
{
    ...

    public function mountWithSorting()
    {
        //
    }

    public function updatingWithSorting($name, $value)
    {
        //
    }

    public function updatedWithSorting($name, $value)
    {
        //
    }

    public function hydrateWithSorting()
    {
        //
    }

    public function dehydrateWithSorting()
    {
        //
    }

    public function renderingWithSorting()
    {
        //
    }

    public function renderedWithSorting($view)
    {
        //
    }
}
← Previous Topic

Flash Messages

Next Topic →

Loading States