laracast 這篇添加可以加入 max length 的方法跟全局組件設定。

Max Length

這個設計跟原先添加設計方法大致相同:

//TextInput
protected int | \Closure | null $maxLength = null;

public function maxLength(int | \Closure | null $length): self
{
    $this->maxLength = $length;

    return $this;
}
public function getMaxLength(): ?int
{
    return $this->evaluate($this->maxLength);
}
//text-input.blade
<input type="text" maxlength="{{ $getMaxLength() }}" wire:model.live="{{ $getName() }}"/>

組件 TestForm 新增兩個來進行驗證:

$nameInput = TextInput::make('name')
            ->maxLength(10)
            ->livewire($this);

        $emailInput = TextInput::make('email')
            ->maxLength(20)
            ->livewire($this);

        return view('livewire.test-form', [
            'nameInput' => $nameInput,
            'emailInput' => $emailInput,
        ]);

<div>
    {{ $nameInput }}

    {{ $emailInput }}
</div>

添加 global configuration

將全局設定傳入closure 依序添加至元件內:

protected static array $configurations = [];

public static function configureUsing(\Closure $configure): void
{
    self::$configurations[] = $configure;
}

public static function make(string $name): self
{
    $input = new self($name);

    foreach (self::$configurations as $configure) {
        $input = $configure($input);
    }

    return $input;
}

//TestForm
TextInput::configureUsing(function (TextInput $input) {
    return $input->maxLength(10);
});
...