Skip to content

Commit 2aae745

Browse files
committed
Implement Attachable contract in EloquentResource
1 parent c1a61c5 commit 2aae745

1 file changed

Lines changed: 31 additions & 1 deletion

File tree

src/Laravel/EloquentResource.php

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
use Tobyz\JsonApiServer\Laravel\Field\ToMany as LaravelToMany;
1919
use Tobyz\JsonApiServer\Pagination\Page;
2020
use Tobyz\JsonApiServer\Resource\AbstractResource;
21+
use Tobyz\JsonApiServer\Resource\Attachable;
2122
use Tobyz\JsonApiServer\Resource\Countable;
2223
use Tobyz\JsonApiServer\Resource\Creatable;
2324
use Tobyz\JsonApiServer\Resource\CursorPaginatable;
@@ -45,6 +46,7 @@ abstract class EloquentResource extends AbstractResource implements
4546
Creatable,
4647
Updatable,
4748
Deletable,
49+
Attachable,
4850
RelatedListable
4951
{
5052
public function resource(object $model, Context $context): ?string
@@ -181,7 +183,7 @@ public function cursorPaginate(
181183
$paginator = $query->cursorPaginate(perPage: $size, cursor: $cursor);
182184
} catch (Exception) {
183185
$key = $after ? 'after' : 'before';
184-
throw (new InvalidPageCursorException())->source(['parameter' => "page[$key]"]);
186+
throw (new InvalidPageCursorException())->source(['parameter' => "[$key]"]);
185187
}
186188

187189
return new Page($paginator->items(), $paginator->onFirstPage(), $paginator->onLastPage());
@@ -255,6 +257,34 @@ public function saveValue(object $model, Field $field, mixed $value, Context $co
255257
}
256258
}
257259

260+
public function attach(
261+
object $model,
262+
Relationship $relationship,
263+
array $related,
264+
Context $context,
265+
): void {
266+
$method = $this->modelMethod($relationship);
267+
$relation = $model->$method();
268+
269+
if ($relation instanceof BelongsToMany) {
270+
$relation->syncWithoutDetaching(new Collection($related));
271+
}
272+
}
273+
274+
public function detach(
275+
object $model,
276+
Relationship $relationship,
277+
array $related,
278+
Context $context,
279+
): void {
280+
$method = $this->modelMethod($relationship);
281+
$relation = $model->$method();
282+
283+
if ($relation instanceof BelongsToMany) {
284+
$relation->detach(new Collection($related));
285+
}
286+
}
287+
258288
public function create(object $model, Context $context): object
259289
{
260290
if (method_exists($this, 'creating')) {

0 commit comments

Comments
 (0)