Example #1
0
 /**
  * Create a new object
  *
  * @param  Request  $request Request object
  * @return ResponseInterface Response for request
  */
 public function post(Request $request, Fractal $fractal, InputGateContract $inputGate)
 {
     $this->beforeRequest($request, func_get_args());
     $input = $request->json()->all();
     if (!is_array($input) || empty($input)) {
         throw new UnprocessableEntityHttpException("Invalid request body");
     }
     $attributes = $originalAttributes = array_get($input, 'data.attributes', []);
     $relationships = array_get($input, 'data.relationships', []);
     $model = $this->getRepository()->model();
     $attributes = $inputGate->process($model, $attributes, 'create');
     $validatedRelationshipData = $this->validateRelationshipData($model, $relationships, 'create');
     if (!empty($attributes) && ($model = $this->getRepository()->create($attributes, app('context'))) && $this->saveRelationshipData($validatedRelationshipData)) {
         return $this->respondWithCreated($fractal->createData(new FractalItem($this->getRepository()->findById($model->id), $this->getTransformer(), $this->getResourceKey())));
     }
     throw ServerErrorHttpException("Unable to save object. Try again later.");
 }
Example #2
0
 /**
  * Update the object
  *
  * @param  Request  $request Request object
  * @param  string $id Unique identifier for the object
  * @return ResponseInterface    Response for object
  */
 public function patch(Request $request, Fractal $fractal, InputGateContract $inputGate)
 {
     $this->beforeRequest($request, func_get_args());
     $id = $this->parseObjectId($request);
     $model = $this->loadAuthorizeObject($id, 'update');
     $input = $request->json()->all();
     if (!is_array($input) || empty($input)) {
         throw new UnprocessableEntityHttpException("Invalid request body");
     }
     $attributes = $originalAttributes = array_get($input, 'data.attributes', []);
     $context = app('context');
     foreach ($context as $key => $value) {
         unset($attributes[$key]);
     }
     $relationships = array_get($input, 'data.relationships', []);
     $attributes = $inputGate->process($model, $attributes, 'update');
     $validatedRelationshipData = $this->validateRelationshipData($model, $relationships, 'update');
     // do update logic
     if ($model->update($attributes) && $this->saveRelationshipData($validatedRelationshipData)) {
         return $this->respondWithUpdated($fractal->createData(new FractalItem($this->loadAuthorizeObject($id, 'update'), $this->getTransformer(), $this->getResourceKey())));
     }
     throw new ServerErrorHttpException("Unable to save object. Try again later.");
 }