dimanche 1 décembre 2019

Avoid Duplication or Error When Updating Form in Laravel

I have 2 tables beneficiaries and addresses joined with relation beneficiary_id as foreign key while each beneficiary record should have 1 address only.

The records are duplicated or fails to insert request() in the second table.

When I use the below code the records are duplicated

public function update(UpdateBeneficiaryRequest $request, Beneficiary $beneficiary, Address $address)
{
    abort_unless(\Gate::allows('beneficiary_edit'), 403);

    $beneficiary->update($request->all());

    // $address->update($request->all());

    $address->fill([
        'beneficiary_id'    => $beneficiary->id,
        'country'           => request('country'),
        'state'             => request('state'),
        'district'          => request('district'),
        'town'              => request('town'),
        'street'            => request('street'),
        'building'          => request('building'),
        'nearby'            => request('nearby')
    ]);

    //->where('id',$id);
    //$address->save();

    $beneficiary->addresses()->save($address);

    return redirect()->route('admin.beneficiaries.index');
}

However when I change the code to get all requests I get an error

public function update(UpdateBeneficiaryRequest $request, Beneficiary $beneficiary, Address $address)
{
    abort_unless(\Gate::allows('beneficiary_edit'), 403);

    $beneficiary->update($request->all());

    $address->update($request->all());

    //->where('id',$id);
    //$address->save();

    $beneficiary->addresses()->save($address);

    return redirect()->route('admin.beneficiaries.index');
}

Error Message:

SQLSTATE[HY000]: General error: 1364 Field 'country' doesn't have a default value (SQL: insert into addresses (beneficiary_id, updated_at, created_at) values (1, 2019-12-02 02:07:27, 2019-12-02 02:07:27))

In the second option the request aren't sent according to table structure

beneficiaries table structure

beneficiaries table structure

addresses table structure addresses table structure

How to avoid records duplication while updating form and get all request to be inserted in the right tables.

I've also used update() and updateOrCreate() functions however both ended in the same result

Please note I'm currently using 2 tables while the target to use 5 tables for 1 form.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire