Skip to content

Commit

Permalink
Add support for updating relationships on resources
Browse files Browse the repository at this point in the history
Not yet linked as direct controller actions
  • Loading branch information
huntie committed May 7, 2016
1 parent 963a3b4 commit 90a2bf0
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/Http/Controllers/JsonApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,58 @@ public function destroyAction(Request $request, $record)
return new JsonApiResponse(null, Response::HTTP_NO_CONTENT);
}

/**
* Update a named many-to-one relationship association on a specified record.
* http://jsonapi.org/format/#crud-updating-to-one-relationships
*
* @param Request $request
* @param Model|int $record
* @param string $relation
* @param string|null $foreignKey
*
* @return JsonApiResponse
*/
public function updateToOneRelationship(Request $request, $record, $relation, $foreignKey = null)
{
$record = $record instanceof Model ? $record : $this->findModelInstance($record);
$data = (array) $request->input('data');

$record->update([($foreignKey ?: $relation . '_id') => $data['id']]);

return new JsonApiResponse(null, Response::HTTP_OK);
}

/**
* Update named many-to-many relationship entries on a specified record.
* http://jsonapi.org/format/#crud-updating-to-many-relationships
*
* @param Request $request
* @param Model|int $record
* @param string $relation
*
* @return JsonApiResponse
*/
public function updateToManyRelationship(Request $request, $record, $relation)
{
$record = $record instanceof Model ? $record : $this->findModelInstance($record);
$relationships = (array) $request->input('data');
$items = [];

foreach ($relationships as $item) {
$items[$item['id']] = $item['attributes'];
}

if ($request->method() === 'PATCH') {
$record->{$relation}()->sync($items);
} else if ($request->method() === 'POST') {
$record->{$relation}()->sync($items, false);
} else if ($request->method() === 'DELETE') {
$record->{$relation}()->detach(array_pluck($relationships, 'id'));
}

return new JsonApiResponse(null, Response::HTTP_OK);
}

/**
* Return an instance of the resource by primary key.
*
Expand Down

0 comments on commit 90a2bf0

Please sign in to comment.