Preferred way to trim input?

Hi there. Input isn’t passed through Laravel’s TrimStrings middleware so code like below might return values with extra spaces:

$this->validate(['name' => 'required']);

I’ve noticed that the LivewireServiceProvider ignores TrimStrings and ConvertEmptyStringsToNull on purpose, and Caleb has also commented about it here: https://github.com/livewire/livewire/issues/354#issuecomment-553109110

What is the preferred way to trim user input seeing it’s not handled by the framework automatically?

Here’s a copy and paste from a class where keep all my input manipulators that does this.

class InputCleaner
{
    public static function string($input)
    {
        if (blank($input)) {
            return null;
        }
        return Str::of($input)->trim()->title();
    }

Just return the line above the title if you don’t need title case. I’m also thinking of overriding and expanding livewire’s validation to suit what I need, so that’s an option too.

Edit: I edited the function after looking at it again, just remove title off the chain if you don’t need it.

Hi xxdalexx. Thanks. How would you go about calling your escaping method?

Would you call it manually before validation?

public function create()
{
    $this->name = static::string($this->name);

    Repo::create(
        $this->validate(['name' => 'required|max:32|unique:repos'])
    );

    session()->flash('message', 'Repository "'.$this->name.'" was created.');
}

This would work but creates a small situation I’d like to avoid…

If you call it but validation fails, $name would be left containing the trimmed version and this would update the version the user can see. If I wanted to avoid this I could capture the original inputs, check them and replace them if a validation exception occurs:

public function create()
{
    $name = $this->name;

    try {
        $this->name = trim($this->name); // whatever cleaning method

        Repo::create(
            $this->validate(['name' => 'required|max:32|unique:repos'])
        );
    } catch (\Illuminate\Validation\ValidationException $e) {
        $this->name = $name; // replace the original version so what the user sees doesn't change
        throw $e;
    }

    session()->flash('message', 'Repository "'.$this->name.'" was created.');
}

This is rather manual and wordy.

I’m wondering if it’s possible and a good idea for Livewire to change the public properties back to their original values in the case of a ValidationException.

What do you think?

I personally do it in your first way, I don’t care that the users version is trimmed and capitalized.