Search code examples
phplaravellaravel-livewire

Validate Livewire public property against existing table in Laravel 9


I have a column named 'workorder_number' which is unique by default. I am adding a feature allowing my dispatchers to clone an existing work order and all its properties(cloning works if I hard-code a unique work order value).

Within the work order view, I added a single input form with a public property called 'new_workorder_number'. When I try to validate the value against the 'workorders' model, I get the error No property found for validation: [447747] *447744 is the 'new_workorder_number' value I entered.

How can I validate a public property that is not a column in the database to an existing column?

edit.php

...
public $new_workorder_number;

public function cloneWorkorder($id)
{
    $this->validate([
        $this->new_workorder_number => 'required|unique:workorders|min:4',
    ]);
...

edit.blade.php

...
<form wire:submit.prevent="cloneWorkorder({{$workorder->id}})" method="PUT">
    <div class="mb-4">
        <div class="grid grid-cols-2 gap-2">
          <div class="col-span-1">
            <input id="new_workorder_number"
                   wire:model.defer="new_workorder_number"
                   placeholder="New Work Order Number">
          </div>
          <div class="col-span-1">
            <button type="submit">
                Clone
            </button>
          </div>
       </div>
    </div>
</form>
...

Solution

  • You're using your validation wrong. Validating in Livewire is basically the same as in Laravel. If you change your validation as following, it should work:

    $this->validate([
        'new_workorder_number' => 'required|unique:workorders,id|min:4',
    ]);
    

    I changed 2 things:

    • Changed the key, since that is the property that needs to be validated on the Livewire component (hence the "no property found exception").
    • Changed your unique validation rule to specify which column the unique should check, as how it's described in the docs. When you check the source code for the unique validation (Illuminate\Validation\Concerns\ValidatesAttributes::validateUnique) you will see that when you don't pass a second parameter, it will guess based on implicit attributes and otherwise returns the attribute, which is the key you're validating. Since you don't have the column new_workdorder_number on your table, it will throw an unknown column exception.