Last active
August 17, 2022 06:49
-
-
Save lazerg/161171df4ff61037c00799d31d56a436 to your computer and use it in GitHub Desktop.
Laravel Nova Field - Editing array of objects using built-in KeyValue Field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
}) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage in resources