Skip to content

Commit

Permalink
Merge pull request #9 from ezra-obiwale/wip
Browse files Browse the repository at this point in the history
Convert relation to camel case if it doesn't exist on model before ta…
  • Loading branch information
ezra-obiwale authored Jan 15, 2018
2 parents 27b1f38 + 6e925b4 commit 130e0d9
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Controllers/Traits/Attachable.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ protected function syncModel() {
return $this->model();
}

private function treatRelation($model, &$relation) {
if (!method_exists($model, $relation)) {
// change relation to camel case
$relation = camel_case(str_replace('-', '_', $relation));
}
}

/**
* Fetches a paginated list of related items
*
Expand All @@ -52,6 +59,7 @@ public function attached($id, $relation) {
$model = is_object($model)
? $model->findOrFail($id)
: $model::findOrFail($id);
$this->treatRelation($model, $relation);
$list = $model->$relation()->simplePaginate();
return $this->paginatedList($list->toArray());
}
Expand All @@ -78,6 +86,7 @@ public function attach($id, $relation, $paramKey = null)
if (!$model) return $this->notFoundError();
try {
$items = request()->input($paramKey);
$this->treatRelation($model, $relation);
$model->$relation()->syncWithoutDetaching($items);
return response()->json([
'status' => 'ok'
Expand Down Expand Up @@ -111,6 +120,7 @@ public function detach($id, $relation, $paramKey = null)
if (!$model) return $this->notFoundError();
try {
$items = request()->input($paramKey);
$this->treatRelation($model, $relation);
$model->$relation()->detach($items);
return response()->json([
'status' => 'ok'
Expand Down Expand Up @@ -144,6 +154,7 @@ public function sync($id, $relation, $paramKey = null)
if (!$model) return $this->notFoundError();
try {
$items = request()->input($paramKey);
$this->treatRelation($model, $relation);
$resp = $model->$relation()->sync($items);
$resp['added'] = $resp['attached'];
$resp['removed'] = $resp['detached'];
Expand Down

0 comments on commit 130e0d9

Please sign in to comment.