Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

codingwithrk's avatar

Displaying error at update for unique

class Create extends Component { #[Rule('required', message: 'Name is required')] #[Rule('unique:products,name', message: 'Product name already available', onUpdate: false)] public $name;

#[Rule('required', message: 'Status is required')]
public $status;

public $type;
public $id;

public function mount()
{
    if ($this->type == 'edit') {
        $data = Product::where('id', $this->id)->first();

        $this->name = $data->name;
        $this->status = $data->status;
    }
}

public function save()
{
    $this->validate();

    $faker = Factory::create();
    Product::create([
        'name' => $this->name,
        'status' => $this->status,
        'color' => $faker->hexColor(),
        'created_user_name' => \Auth::user()->name,
        'user_id' => \Auth::user()->id,
    ]);
    return redirect()->route('products')->with('success', 'New product added');
}

public function update()
{
    $this->validate();
    Product::find($this->id)->update([
        'name' => $this->name,
        'status' => $this->status,
    ]);
    return redirect()->route('products')->with('success', 'Product data updated');
}

public function render()
{
    return view('livewire.admin.products.create');
}

}

0 likes
3 replies
ramonrietdijk's avatar

You've only shared a snippet of your code. What exactly is your question?

codingwithrk's avatar

@ramonrietdijk When I want to update just status, at that time it throws an error 'Product name already available', But I am unable to skip that unique rule for that ID like we do in Laravel like this 'year' => 'required|unique:years,year,'.$id,

ramonrietdijk's avatar

@codingwithrk In that case I'd recommend adding a rules() method to create the validation. You'll have a lot more control this way as you can use Laravel's rule classes.

Example:

public function rules()
{
    return [
        'name' => [
            'required',
            Rule::unique('products')->ignore($this->id), 
        ],
    ];
}

To clarify, the onUpdate option that you've used means that the validation is, or is not, performed directly after the value has changed. It doesn't mean that the rule won't be applied if a model is updated.

Also a small note, Livewire recommends using #[Validate] instead of #[Rule] as described here. It won't break, but it's recommended to use the new syntax.

1 like

Please or to participate in this conversation.