masmerise / livewire-toaster

Beautiful toast notifications for Laravel / Livewire.
MIT License
342 stars 22 forks source link

Toasting on validation error #5

Closed greggh closed 1 year ago

greggh commented 1 year ago

I have a wire:model and a form that are working fine for adding an entry with field name of description. I also have a rule for "description" that it has to be min 6 characters. I use $this->validate() to validate before created the new entry.

In my blade I have:

` @error('description')

@enderror

`

This only happens once, because the script is already there, so it doesn't run again.

What's the proper way to Toaster on a validation error in a livelier component?

mabdullahsari commented 1 year ago

You can hook into the dehydrate lifecycle method and check whether the ErrorBag has any errors. If yes, you can forward the error messages to Toaster.

Something like this should work (not tested):

public function dehydrate()
{
    $errors = $this->getErrorBag();

    if ($errors->has('description')) {
        Toaster::error($errors->get('description'));
    }
}

You can create a trait or something similar if you need to reuse the logic.

greggh commented 1 year ago

That is awesome. Thank you for that. Works great. Just had to deal with the $errors->get() returning an array instead of a string. All working now!