Skip to content

Instantly share code, notes, and snippets.

@lazerg
Last active August 17, 2022 06:49
Show Gist options
  • Save lazerg/161171df4ff61037c00799d31d56a436 to your computer and use it in GitHub Desktop.
Save lazerg/161171df4ff61037c00799d31d56a436 to your computer and use it in GitHub Desktop.
Laravel Nova Field - Editing array of objects using built-in KeyValue Field
<?php
namespace App\Nova\Fields;
use Illuminate\Http\Resources\MergeValue;
use Laravel\Nova\Fields\KeyValue;
use Str;
trait HasJsonField
{
/**
* Array of objects to be displayed in the JSON field.
*
* @param string $name
* @param string $attribute
* @param callable|null $configureKeyValue
* @return MergeValue
*/
public function arrayOfJson(string $name, string $attribute = '', callable $configureKeyValue = null): MergeValue
{
if (!$attribute) {
$attribute = Str::snake($name);
}
return $this->merge(
collect($this->resource->{$attribute})
->map(function (array $field, int $index) use ($configureKeyValue, $attribute, $name) {
$number = "#" . ($index + 1);
$component = KeyValue::make(
"$name $number",
"$attribute->$index"
);
return $configureKeyValue
? $configureKeyValue($component)
: $component;
})
);
}
}
@lazerg
Copy link
Author

lazerg commented Aug 17, 2022

Usage in resources

$this->arrayOfJson('Payment methods', 'payment_methods',
    fn(KeyValue $component) => $component
        ->disableAddingRows()
        ->disableEditingKeys()
        ->disableDeletingRows()
),

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