Example #1
0
 /**
  * Default handling of PUT request.
  * Must be called explicitly in handlePut function.
  *
  * @param  \EchoIt\JsonApi\Request $request
  * @param  \EchoIt\JsonApi\Model   $model
  * @return \EchoIt\JsonApi\Model
  * @throws Exception
  */
 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;
 }