|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Binaryk\LaravelRestify\Http\Controllers; |
| 4 | + |
| 5 | +use Binaryk\LaravelRestify\Http\Requests\RepositoryAttachRequest; |
| 6 | +use Binaryk\LaravelRestify\Http\Requests\RestifyRequest; |
| 7 | +use DateTime; |
| 8 | +use Illuminate\Support\Arr; |
| 9 | + |
| 10 | +class RepositoryAttachController extends RepositoryController |
| 11 | +{ |
| 12 | + public function __invoke(RepositoryAttachRequest $request) |
| 13 | + { |
| 14 | + $model = $request->findModelOrFail(); |
| 15 | + $repository = $request->repository()->allowToUpdate($request); |
| 16 | + |
| 17 | + return $repository->attach( |
| 18 | + $request, $request->repositoryId, |
| 19 | + collect(Arr::wrap($request->input($request->relatedRepository))) |
| 20 | + ->map(fn ($relatedRepositoryId) => $this->initializePivot( |
| 21 | + $request, $model->{$request->viaRelationship ?? $request->relatedRepository}(), $relatedRepositoryId |
| 22 | + )) |
| 23 | + ); |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * Initialize a fresh pivot model for the relationship. |
| 28 | + * |
| 29 | + * @param RestifyRequest $request |
| 30 | + * @param $relationship |
| 31 | + * @return mixed |
| 32 | + * @throws \Binaryk\LaravelRestify\Exceptions\Eloquent\EntityNotFoundException |
| 33 | + * @throws \Binaryk\LaravelRestify\Exceptions\UnauthorizedException |
| 34 | + */ |
| 35 | + protected function initializePivot(RestifyRequest $request, $relationship, $relatedKey) |
| 36 | + { |
| 37 | + $parentKey = $request->repositoryId; |
| 38 | + |
| 39 | + $parentKeyName = $relationship->getParentKeyName(); |
| 40 | + $relatedKeyName = $relationship->getRelatedKeyName(); |
| 41 | + |
| 42 | + if ($parentKeyName !== $request->model()->getKeyName()) { |
| 43 | + $parentKey = $request->findModelOrFail()->{$parentKeyName}; |
| 44 | + } |
| 45 | + |
| 46 | + if ($relatedKeyName !== ($request->newRelatedRepository()::newModel())->getKeyName()) { |
| 47 | + $relatedKey = $request->findRelatedModelOrFail()->{$relatedKeyName}; |
| 48 | + } |
| 49 | + |
| 50 | + ($pivot = $relationship->newPivot())->forceFill([ |
| 51 | + $relationship->getForeignPivotKeyName() => $parentKey, |
| 52 | + $relationship->getRelatedPivotKeyName() => $relatedKey, |
| 53 | + ]); |
| 54 | + |
| 55 | + if ($relationship->withTimestamps) { |
| 56 | + $pivot->forceFill([ |
| 57 | + $relationship->createdAt() => new DateTime, |
| 58 | + $relationship->updatedAt() => new DateTime, |
| 59 | + ]); |
| 60 | + } |
| 61 | + |
| 62 | + return $pivot; |
| 63 | + } |
| 64 | +} |
0 commit comments