Skip to content

Commit

Permalink
Convert relation to camel case if it doesn't exist on model before ta…
Browse files Browse the repository at this point in the history
…king relationship action
  • Loading branch information
ezra-obiwale committed Jan 15, 2018
1 parent 5dd8093 commit 80cb27e
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 80cb27e

Please sign in to comment.