Last active
June 8, 2021 14:20
-
-
Save ganyicz/9a611f95171c9136758ea2d768eb5458 to your computer and use it in GitHub Desktop.
Laravel Nova - relation fields
This file contains hidden or 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
| // Customer hasOne or belongsTo User | |
| public function fields(Request $request) | |
| { | |
| return [ | |
| Text::make('Heslo', 'password')->onRelation('user'), | |
| ]; | |
| } |
This file contains hidden or 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
| Field::macro('onRelation', function ($relation) { | |
| /** @var \Laravel\Nova\Fields\Field $this */ | |
| return $this | |
| ->withMeta(['__relation' => $relation]) | |
| ->resolveUsing(fn ($value, $model, $attribute) => | |
| optional($model->$relation)->$attribute | |
| ); | |
| }); |
This file contains hidden or 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
| protected static function fillFields(NovaRequest $request, $model, $fields) | |
| { | |
| $model::saved(function ($model) use ($request, $fields) { | |
| $relationFields = $fields | |
| ->filter(fn ($field) => isset($field->meta['__relation'])) | |
| ->groupBy(fn ($field) => $field->meta['__relation']); | |
| foreach ($relationFields as $relation => $fields) { | |
| $relatedModel = $model->$relation()->firstOrNew(); | |
| parent::fillFields($request, $relatedModel, $fields); | |
| $relatedModel->save(); | |
| } | |
| }); | |
| return parent::fillFields($request, $model, $fields->reject(fn ($field) => isset($field->meta['__relation']))); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment