PHPexp logo PHPexp

Laravel Livewire enum type hint

Published on

By default, if you type hint an enum in a Livewire component, you'll get an error. Livewire doesn't support enum type hints out of the box. We can fix this with a lifecycle hook:

use Livewire\Component;

class YourComponent extends Component
    public UserRole $user_role = UserRole::ADMIN;

    public function updatingUserRole(&$value)
        $value = $value instanceof UserRole ? $value : UserRole::from($value);

The updatingUserRole lifecycle hook can change the value before the property is set. $value is passed by reference so that we can cast it to an enum before Livewire assigns it to the property.

Level up your Laravel deployments

If you aren't happy with your current deployment strategy for your Laravel apps, check out my premium deployment script.

Deploy with GitHub Actions Deploy with GitLab CI/CD