feat: Salva le relationships durante il salvataggio

This commit is contained in:
Maicol Battistini 2022-01-10 16:59:38 +01:00
parent f0982961c0
commit 33131e8d17
No known key found for this signature in database
GPG Key ID: 4FDB0F87CDB1D34A
1 changed files with 14 additions and 0 deletions

View File

@ -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'));