Enable parent to be set during creation via API (#39)

* Enable parent to be set during creation via API

Sets the parent ID as long as it exists and is a top-level primary tag.
If it's not, it'll simply be ignored. Position is set automatically to
be one higher than the current highest, or 0 if parent has no children.

Example data (in addition to the usual attributes):
```
"relationships": {
    "parent": {
        "data": {
            "id": 1
        }
    }
}
```

* Add support for creating top-level tags

To set a top-level primary tag, pass parent id of 0
For a secondary tag, pass null or remove it from the request
To set as a child, pass the parent tag's id
This commit is contained in:
Dave Shoreman 2017-04-11 05:24:35 +01:00 committed by Toby Zerner
parent 61321c32ed
commit f61d834a76
2 changed files with 20 additions and 0 deletions

View File

@ -25,6 +25,11 @@ class CreateTagController extends AbstractCreateController
*/
public $serializer = TagSerializer::class;
/**
* {@inheritdoc}
*/
public $include = ['parent'];
/**
* @var Dispatcher
*/

View File

@ -51,6 +51,21 @@ class CreateTagHandler
array_get($data, 'attributes.isHidden')
);
$parentId = array_get($data, 'relationships.parent.data.id');
if ($parentId !== null) {
$rootTags = Tag::whereNull('parent_id')->whereNotNull('position');
if ($parentId === 0) {
$tag->position = $rootTags->max('position') + 1;
} elseif ($rootTags->find($parentId)) {
$position = Tag::where('parent_id', $parentId)->max('position');
$tag->parent()->associate($parentId);
$tag->position = $position === null ? 0 : $position + 1;
}
}
$this->validator->assertValid($tag->getAttributes());
$tag->save();