Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save domthomas-dev/b4a25dd5840bfd736a81c90a8f0a768c to your computer and use it in GitHub Desktop.
Save domthomas-dev/b4a25dd5840bfd736a81c90a8f0a768c to your computer and use it in GitHub Desktop.
<?php
namespace App\Http\Livewire\Traits;
use Illuminate\Support\Str;
trait ConvertEmptyStringsToNull
{
public function updatedConvertEmptyStringsToNull(string $name, mixed $value): void
{
if (! $this->shouldConvertValue($value, $name)) {
return;
}
$value = trim($value);
$value = $value === '' ? null : $value;
if (Str::of($name)->contains('.')) {
$nestedTargetName = Str::of($name)->beforeLast('.');
$nestedPropertyName = Str::of($name)->afterLast('.');
$nested = data_get($this, $nestedTargetName);
data_set($nested, $nestedPropertyName, $value);
data_set($this, $nestedTargetName, $nested);
return;
}
data_set($this, $name, $value);
}
protected function shouldConvertValue(mixed $value, string $name): bool
{
return
is_string($value)
&& (
! property_exists($this, 'convertEmptyStringsExcept')
|| ! in_array($name, $this->convertEmptyStringsExcept)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment