From 33131e8d172dea149411fdf0b5211c5defd09d2b Mon Sep 17 00:00:00 2001 From: Maicol Battistini Date: Mon, 10 Jan 2022 16:59:38 +0100 Subject: [PATCH] =?UTF-8?q?feat:=20=E2=9C=A8=20Salva=20le=20relationships?= =?UTF-8?q?=20durante=20il=20salvataggio?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Http/Controllers/Api/ApiController.php | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/app/Http/Controllers/Api/ApiController.php b/app/Http/Controllers/Api/ApiController.php index 551135588..94a7e9866 100644 --- a/app/Http/Controllers/Api/ApiController.php +++ b/app/Http/Controllers/Api/ApiController.php @@ -7,13 +7,22 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Http\Response; +use Illuminate\Support\Arr; use Maicol07\LaravelJsonApiResource\Http\Resource\JsonApi\Resource; use Maicol07\LaravelJsonApiResource\Http\Resource\JsonApi\ResourceCollection; class ApiController extends Controller { + /** + * The parent model used by the controller. + */ protected string|Model $model = Model::class; + /** + * @var array{string: Model | array} + */ + protected array $relationships = []; + /** * Display a listing of the resource. */ @@ -31,6 +40,11 @@ class ApiController extends Controller $instance = new $this->model(); $instance->fill($request->input('data.attributes')); + foreach ($request->input('data.relationships') as $key => $data) { + $model = $this->relationships[$key]; + $instance->{$key}()->associate($model::find(Arr::get($data, 'data.id'))); + } + $created = $instance->save(); return $created ? new Resource($instance) : $this->error(Response::HTTP_INTERNAL_SERVER_ERROR, __('Impossibile creare la risorsa'));