From 15615df6d38bbf7138461a3466fa2a62dc08d761 Mon Sep 17 00:00:00 2001 From: Guido Date: Thu, 16 Feb 2023 13:18:31 +0100 Subject: [PATCH] Fix Polymorphic Relationships --- src/Flexible.php | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/Flexible.php b/src/Flexible.php index ceba13b1..35fe2cc9 100644 --- a/src/Flexible.php +++ b/src/Flexible.php @@ -404,13 +404,31 @@ protected function extractValue(NovaRequest $request, $attribute) return; } - if (! is_array($value)) { - throw new \Exception('Unable to parse incoming Flexible content, data should be an array.'); + if (!is_array($value)) { + return $this->mapPolymorphicRelationships($value); } return $value; } + /** + * Try decoding value to array to make it work with Polymorphic Relationships + * @param string $value + * @return \Illuminate\Support\Collection + * @throws \Exception + */ + protected function mapPolymorphicRelationships(string $value) { + if (!$value = @json_decode($value, true)) { + throw new \Exception('Unable to parse incoming Flexible content, data should be an array.'); + } + return collect($value)->map(function ($item) { + $item['attributes'] = collect($item['attributes'])->mapWithKeys(function ($layout, $key) use ($item) { + return [str_replace("{$item['key']}__", "", $key) => $layout]; + })->toArray(); + return $item; + }); + } + /** * Resolve all contained groups and their fields *