PHPexp logo PHPexp

TrimStrings and ConvertEmptyStringsToNull in Laravel Livewire

Published on

Laravel Livewire does not automatically trim strings, it also doesn't convert empty strings to null. This is not a bug. Caleb Porzio has said on GitHub that not trimming and converting to null is desired behaviour.

Normally when using Laravel, strings are automatically trimmed by the TrimStrings middleware. Empty strings are automatically converted to null by the ConvertEmptyStringsToNull middleware. This is what most Laravel developers have gotten used to. Manually reproducing this behaviour in all your Livewire components is error-prone.

Automatically trimming and converting to null

We can add automatic input trimming to our Livewire components with this trait:

<?php

namespace App\Http\Livewire;

trait TrimStringsAndConvertEmptyStringsToNull
{
    public function updatedTrimStringsAndConvertEmptyStringsToNull($name, $value)
    {
        if (is_string($value)) {
            $trimmed = trim($value);
            
            data_set($this, $name, $trimmed === '' ? null : $trimmed);
        }
    }
}

Every property that gets updated will be passed to this lifecycle hook. If you use this trait in your components, strings will behave just like they do in normal Laravel controllers. This lifecycle hook is magic, it works because the method has the same name as the trait.

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