Best way to save/update data from json to Laravel model with relationships

Viewed 87

I have two models:

Models/Arrival.php:

protected $guarded = [];

public function nomenclatures()
{
    return $this->hasMany(ArrivalNomenclature::class, 'arrival_id', 'id');
}

public function warehouses()
{
    return $this->belongsTo(Warehouse::class, 'warehouse_id', 'id');
}

Models/ArrivalNomenclatures.php:

protected $guarded = ['id'];

public function nomenclatures()
{
    return $this->belongsTo(Nomenclature::class, 'nomenclature_id');
}

public function arrivals()
{
    return $this->belongsTo(Arrival::class, 'arrival_id');
}

I need to save from json:

{
"type": "provider",
"invoice": "123yk43",
"filial_id": 10,
"warehouse_id": 6,
"provider_id": 9,
"responsible": "ttt",
"user_id": "4",
"carried_out": 0,
"nomenclatures": [
    {
        "confirmed": 0,
        "nomenclature_id": 1,
        "price": 1337,
        "quantity": 10,
    },
    {
        "confirmed": 0,
        "nomenclature_id": 1,
        "price": 1337,
        "quantity": 10,

    }
    ....
]}

Creation raises no questions. How to update models correctly?

            $arrival = Arrival::findOrFail($id);
            $arrival->update($dataArrival);

            ArrivalNomenclature::where('arrival_id', $arrival->id)->delete();

            foreach ($request->nomenclatures as $nomenclature) {
                $data[] = new ArrivalNomenclature($nomenclature);
            }

            $arrival->nomenclatures()->saveMany($data);

At the moment I find it by id and make an update. Then I delete all child records by id. I create an array of models in a loop and use the saveMany () method to save it to the database. Is there a nicer way?

0 Answers
Related