Questions & Answers

Error handling when user modifies the wire:model by inspect element in the browser

I'm using livewire and Laravel in my forms.

A problem that I noticed is that if we have an input like this:

<input type="text" wire:model.debounce.500ms="first_name" id="first_name" name="first_name" class="form-control"/>

Then when user modifies the wire:model.debounce.500ms attribute value or totally removes that in inspect element, after typing into that input because livewire can't find the model name so it throws an error and the error will be shown in a modal that says this:

Too few arguments to function Illuminate\Support\Str::studly(), 0 passed in C:\xampp\htdocs\laravel-project\example\vendor\livewire\livewire\src\helpers.php on line 13 and exactly 1 expected

So I want to handle these errors. I know I can change APP_DEBUG in .env file to false but again it shows the error modal saying there is a 500 error but I don't want the user's manipulations affects the livewire or at least not to show these modals and just detect them.

Answers(1) :

You can use a mutation observer to watch for mutations on your inputs.

We can use document.evaluate to find all wire:model elements (see this answer)

let attributeObserver = new MutationObserver(function(mutations) {
    // Do something

let wireModels = document.evaluate('//*/attribute::*[starts-with(name(), "wire:model")]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

for (var i = 0; i < wireModels.snapshotLength; i++ ) {
   let element = nodesSnapshot.snapshotItem(i).ownerElement.
   attributeObserver.observe(element, { attributes: true });
2023-01-20 23:30:11
I tried to get the modified element and set the modified attribute to the old value but the oldValue key that mutation variable returns, is null
2023-01-20 23:30:11
And another problem is that it will run MutationObserver when the page reloads.
2023-01-20 23:30:11
Have you set attributeOldValue to true in your config?