|
18 | 18 | use Tobyz\JsonApiServer\Laravel\Field\ToMany as LaravelToMany; |
19 | 19 | use Tobyz\JsonApiServer\Pagination\Page; |
20 | 20 | use Tobyz\JsonApiServer\Resource\AbstractResource; |
| 21 | +use Tobyz\JsonApiServer\Resource\Attachable; |
21 | 22 | use Tobyz\JsonApiServer\Resource\Countable; |
22 | 23 | use Tobyz\JsonApiServer\Resource\Creatable; |
23 | 24 | use Tobyz\JsonApiServer\Resource\CursorPaginatable; |
@@ -45,6 +46,7 @@ abstract class EloquentResource extends AbstractResource implements |
45 | 46 | Creatable, |
46 | 47 | Updatable, |
47 | 48 | Deletable, |
| 49 | + Attachable, |
48 | 50 | RelatedListable |
49 | 51 | { |
50 | 52 | public function resource(object $model, Context $context): ?string |
@@ -181,7 +183,7 @@ public function cursorPaginate( |
181 | 183 | $paginator = $query->cursorPaginate(perPage: $size, cursor: $cursor); |
182 | 184 | } catch (Exception) { |
183 | 185 | $key = $after ? 'after' : 'before'; |
184 | | - throw (new InvalidPageCursorException())->source(['parameter' => "page[$key]"]); |
| 186 | + throw (new InvalidPageCursorException())->source(['parameter' => "[$key]"]); |
185 | 187 | } |
186 | 188 |
|
187 | 189 | return new Page($paginator->items(), $paginator->onFirstPage(), $paginator->onLastPage()); |
@@ -255,6 +257,34 @@ public function saveValue(object $model, Field $field, mixed $value, Context $co |
255 | 257 | } |
256 | 258 | } |
257 | 259 |
|
| 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 | + |
258 | 288 | public function create(object $model, Context $context): object |
259 | 289 | { |
260 | 290 | if (method_exists($this, 'creating')) { |
|
0 commit comments