Skip to content

Instantly share code, notes, and snippets.

@imliam

imliam/README.md Secret

Created September 7, 2020 19:41
Show Gist options
  • Save imliam/3709ceafb0bd60ea8026b5c936f591ac to your computer and use it in GitHub Desktop.
Save imliam/3709ceafb0bd60ea8026b5c936f591ac to your computer and use it in GitHub Desktop.

Adding this trait to a Livewire component will automatically trigger methods when nested values get updated.

For example, by default, if you use wire:model="foo.bar" on a Livewire component, this will only trigger the updatingFoo() and updatedFoo() methods on the component if they exist.

With this trait, it will also trigger the updatingFooBar() and updatedFooBar() methods.

<?php
namespace App\Http\Livewire\Traits;
use Illuminate\Support\Str;
trait UpdatesNestedValues
{
public function updated($field, $value)
{
$this->updateNestedValue('updated', $field, $value);
}
public function updating($field, $value)
{
$this->updateNestedValue('updating', $field, $value);
}
protected function updateNestedValue(string $event, string $field, $value)
{
if (!Str::contains($field, '.')) {
return;
}
$eventMethodName = $event . Str::of($field)->replace('.', '_')->studly();
if (method_exists($this, $eventMethodName)) {
return $this->{$eventMethodName}($value);
}
}
}
@Xsaven
Copy link

Xsaven commented Oct 13, 2021

It's not clear why this is, since Livewire and so know how to do that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment