post request on To-Many relationship

@param ApiRequest $request
@param Model $resourceModel
@return Model
@throws \Exception
348442
public function relatedPost(ApiRequest $request, $resourceModel)
    {
        $requestModel = $request->asRequestModel();

        $this->validate($requestModel, $this->getCreatingRules());

        $ids = (array)$requestModel->id();

        /** @var BelongsToMany $relation */
        $relation = $this->getRelation($resourceModel);
        $this->beforeCreating($ids, $relation);

        $requestModel->map(function (RequestModel $model) use ($relation) {
            $this->createRelationshipModel($relation, $model);
        });

        return $this->getRelation($resourceModel->fresh())->get();
    }
320816
protected function processPost(Request $request)
    {
        $resource = $this->getResourceManager()->createNewInstance();
        return $this->processAction($request, 'POST', $resource);
    }
578033
public function sendRequest(ApiKey $apiKey, RestRequest $request)
    {
        $hmac = $this->generateHmac($apiKey->getPrivateKey(), $request->getEndpoint(), array_merge($request->getQueryData(), $request->getPostData()));

        $client = new Client([
            'base_uri' => $request->getHost()
        ]);
        
        $args = [
            'auth' => [$apiKey->getPublicKey(), $hmac],
            'headers' => [
                'Accept' => 'application/json'
            ]
        ];
        
        if ($request->getRequestMethod() === 'POST') {
            $args['form_params'] = $request->getPostData();
        } else {
            $args['query'] = $request->getQueryData();
        }
        
        try {
            $responseRaw = $client->request($request->getRequestMethod(), $request->getEndpoint(), $args);
        } catch (RequestException $e) {
            if (!$e->hasResponse()) {
                throw new Exception('Cannot send REST request.', 0, $e);
            }
            
            $responseRaw = $e->getResponse();
        }
        
        return $this->prepareResponse($responseRaw, $request);
    }
55214
public function invoke(AbstractRequest $request)
    {
        $this->invoker->invoke($request);
        $current = clone $request->resourceObject;
        foreach ($request->links as $link) {
            /* @noinspection ExceptionsAnnotatingAndHandlingInspection */
            $nextResource = $this->annotationLink($link, $current, $request);
            $current = $this->nextLink($link, $current, $nextResource);
        }

        return $current;
    }
549804
public function postUpdate(ModelConfigurationInterface $model, Request $request, $id)
    {
        /** @var FormInterface $editForm */
        $editForm = $model->fireEdit($id);
        $item = $editForm->getModel();

        if (is_null($item) || ! $model->isEditable($item)) {
            abort(404);
        }

        $nextAction = $request->input('next_action');

        $backUrl = $this->getBackUrl($request);

        if ($editForm instanceof FormInterface) {
            try {
                $editForm->validateForm($request, $model);

                if ($editForm->saveForm($request, $model) === false) {
                    return redirect()->back()->with([
                        '_redirectBack'       => $backUrl,
                        'sleeping_owl_tab_id' => $request->get('sleeping_owl_tab_id') ?: null,
                    ]);
                }
            } catch (ValidationException $exception) {
                return redirect()->back()
                    ->withErrors($exception->validator)
                    ->withInput()
                    ->with([
                        '_redirectBack'       => $backUrl,
                        'sleeping_owl_tab_id' => $request->get('sleeping_owl_tab_id') ?: null,
                    ]);
            }
        }

        $redirectPolicy = $model->getRedirect();

        if ($nextAction == 'save_and_continue') {
            $response = redirect()->back()->with([
                '_redirectBack'       => $backUrl,
                'sleeping_owl_tab_id' => $request->get('sleeping_owl_tab_id') ?: null,
            ]);

            if ($redirectPolicy->get('edit') == 'display') {
                $response = redirect()->to(
                    $model->getDisplayUrl()
                )->with([
                    '_redirectBack'       => $backUrl,
                    'sleeping_owl_tab_id' => $request->get('sleeping_owl_tab_id') ?: null,
                ]);
            }
        } elseif ($nextAction == 'save_and_create') {
            $response = redirect()->to($model->getCreateUrl($request->except([
                '_redirectBack',
                '_token',
                'url',
                'next_action',
            ])))->with([
                '_redirectBack'       => $backUrl,
                'sleeping_owl_tab_id' => $request->get('sleeping_owl_tab_id') ?: null,
            ]);
        } else {
            $response = redirect()->to($request->input('_redirectBack', $model->getDisplayUrl()));
        }

        return $response->with('success_message', $model->getMessageOnUpdate());
    }
817605
public function postAction(Request $request)
    {
        $name = $request->get('position');

        try {
            if (null == $name) {
                throw new RestException(
                    'There is no position-name for the given name'
                );
            }

            $em = $this->getDoctrine()->getManager();
            $position = new Position();
            $position->setPosition($name);

            $em->persist($position);
            $em->flush();

            $view = $this->view($position, 200);
        } catch (EntityNotFoundException $enfe) {
            $view = $this->view($enfe->toArray(), 404);
        } catch (RestException $re) {
            $view = $this->view($re->toArray(), 400);
        }

        return $this->handleView($view);
    }
150152
public function postAction(Request $request)
    {
        try {
            $data = $request->request->all();
            $data['type'] = OrderType::MANUAL;

            $order = $this->getManager()->save(
                $data,
                $this->getLocale($request),
                $this->getUser()->getId()
            );

            $view = $this->view($order, 200);
        } catch (OrderDependencyNotFoundException $exc) {
            $exception = new EntityNotFoundException($exc->getEntityName(), $exc->getId());
            $view = $this->view($exception->toArray(), 400);
        } catch (MissingOrderAttributeException $exc) {
            $exception = new MissingArgumentException(self::$orderEntityName, $exc->getAttribute());
            $view = $this->view($exception->toArray(), 400);
        }

        return $this->handleView($view);
    }
896159
public function handlePutDefault(Request $request, $model)
    {
        if (empty($request->id)) {
            throw new Exception(
                'No ID provided',
                static::ERROR_SCOPE | static::ERROR_NO_ID,
                BaseResponse::HTTP_BAD_REQUEST
            );
        }

        $updates = $this->parseRequestContent($request->content, $model->getResourceType());

        $model = $model::find($request->id);
        if (is_null($model)) {
            return null;
        }

        // fetch the original attributes
        $originalAttributes = $model->getOriginal();

        // apply our updates
        $model->fill($updates);

        // ensure we can get a succesful save
        if (!$model->save()) {
            throw new Exception(
                'An unknown error occurred',
                static::ERROR_SCOPE | static::ERROR_UNKNOWN,
                BaseResponse::HTTP_INTERNAL_SERVER_ERROR
            );
        }

        // fetch the current attributes (post save)
        $newAttributes = $model->getAttributes();

        // loop through the new attributes, and ensure they are identical
        // to the original ones. if not, then we need to return the model
        foreach ($newAttributes as $attribute => $value) {
            if (! array_key_exists($attribute, $originalAttributes) || $value !== $originalAttributes[$attribute]) {
                $model->markChanged();
                break;
            }
        }

        return $model;
    }
894274
protected function fillAttributeFromRequest(NovaRequest $request, $requestAttribute, $model, $attribute)
    {
        foreach ($this->meta['types'] as $type) {

            if($request->get($attribute) == $type['value']) {
                $relatedModel = new $type['value'];

                if($this->mapToKey($type['value']) == $model->{$this->attribute . '_type'}) {
                    $relatedModel = $relatedModel->newQuery()->findOrFail($model->{$this->attribute . '_id'});
                } elseif(! is_null($model->{$this->attribute . '_type'})) {
                    $oldRelatedClass = $this->mapToClass($model->{$this->attribute . '_type'});
                    $oldRelatedModel = (new $oldRelatedClass)->newQuery()->findOrFail($model->{$this->attribute . '_id'});
                    $oldRelatedModel->delete();
                }

                foreach ($type['fields'] as $field) {
                    $field->fill($request, $relatedModel);
                }

                $relatedModel->save();

                $model->{$this->attribute.'_id'} = $relatedModel->id;
                $model->{$this->attribute.'_type'} = $this->mapToKey($type['value']);
            }

        }
    }
571766
protected function load($model, $request)
    {
        $model->load($request->getQueryParams());

        return $model->load($request->getBodyParams());
    }
142230
public function update($request) {
        $this->resolveModel();
        $model = Dir::apiModel($this->model);
        $modelFind = $model::find($request->id);

        if(!empty($request->relationalModel)) {
            $idRelationalModel = trim(strtolower($request->relationalModel), 's');
            $idRelationalModel =  $idRelationalModel.'Id';
            if($modelFind->$idRelationalModel != $request->idRelational) killer('400');
        }

        foreach($modelFind->getTuples() as $tuple)
            if(!empty($request->$tuple))
                $modelFind->$tuple = $request->$tuple;

        $modelFind->update();
        return $modelFind;
    }
1257529
public function dispatch(Request $request)
    {
        // determine resource
        $resourceParts = explode('/', $request->getResource());
        $resourceName = $resourceParts[0];
        $subResourceName = false;
        if (count($resourceParts) > 1) {
            $subResourceName = $resourceParts[1];
        }

        try {
            $resourceMetadata = $this->resourceMetadataFactory->getMetadataByResourceName($resourceName);
        } catch (ResourceMappingException $e) {
            throw Exception::resourceNotFound($resourceName, 404, $e);
        }

        // determine service
        if ($subResourceName) {
            if (!$resourceMetadata->hasSubResource($subResourceName)) {
                throw Exception::resourceNotFound($request->getResource());
            }

            $subResourceMapping = $resourceMetadata->getSubResource($subResourceName);
            $service = $this->serviceLocator->get($subResourceMapping['service']);
        } else {
            $service = $this->serviceLocator->get($resourceMetadata->getService());
        }

        $this->registerListeners($service);

        $event = new RequestEvent();
        $event->setRequest($request);

        $this->eventManager->dispatch($request->getMethod(), $event);

        return $event->getData();
    }
255038
public function show($request) {
        $this->resolveModel();
        $model = Dir::apiModel($this->model);

        if(empty($request->relationalModel))
            return $model::find($request->id);
        else {
            $modelRelational = trim(strtolower($request->relationalModel), 's');
            return $model::where([
                $model::EQUALS(
                    $modelRelational.'Id',
                    $request->idRelational
                ),
                $model::EQUALS(
                    'id',
                    $request->id
                )
            ]);
        }
    }
513798
public function postAction(Request $request, $attributeId)
    {
        try {
            $attributeValue = $this->getManager()->save(
                $request->request->all(),
                $this->getLocale($request),
                $attributeId
            );
            $view = $this->view($attributeValue, 200);
        } catch (AttributeDependencyNotFoundException $exc) {
            $exception = new EntityNotFoundException($exc->getEntityName(), $exc->getId());
            $view = $this->view($exception->toArray(), 400);
        } catch (MissingAttributeValueException $exc) {
            $exception = new MissingArgumentException(self::$entityName, $exc->getAttribute());
            $view = $this->view($exception->toArray(), 400);
        }

        return $this->handleView($view);
    }
73692
public function removeResourceModelAction(ResourceModel $resourceModel)
    {
        $this->checkAccess($resourceModel->getModel()->getWorkspace());
        $this->modelManager->removeResourceModel($resourceModel);

        return new JsonResponse();
    }
1293325
public function postAction(Request $request)
    {
        try {
            $this->checkArguments($request);
            $contact = $this->getContactManager()->save(
                $request->request->all()
            );
            $apiContact = $this->getContactManager()->getContact(
                $contact,
                $this->getLocale($request)
            );
            $view = $this->view($apiContact, 200);
            $context = new Context();
            $context->setGroups(static::$contactSerializationGroups);
            $view->setContext($context);
        } catch (EntityNotFoundException $enfe) {
            $view = $this->view($enfe->toArray(), 404);
        } catch (MissingArgumentException $maex) {
            $view = $this->view($maex->toArray(), 400);
        } catch (RestException $re) {
            $view = $this->view($re->toArray(), 400);
        }

        return $this->handleView($view);
    }
459329
public function createModel($model, HTTPRequest $request)
    {
        if (!RESTfulAPI::api_access_control($model, $request->httpMethod())) {
            return new RESTfulAPIError(403,
                "API access denied."
            );
        }

        $newModel = Injector::inst()->create($model);

        return $this->updateModel($newModel, $newModel->ID, $request);
    }