Ad

Laravel Integrity Constraint Violation: 1048 Column 'submitform_id' Cannot Be Null In Many-to-many Relationship

- 1 answer

I got an error:

Integrity constraint violation: 1048 Column 'submitform_id' cannot be null

I tried to insert fisherman array data using Insomnia/Postman in POST request

SubmitForm model

public function fisherman()
{
  return $this->belongsToMany(Fisherman::class, 'submitform_fisherman','submitform_id', 'fisherman_id');
}

Fisherman model

public function submitForm()
    {
        return $this->belongsToMany(SubmitForm::class,'submitform_fisherman','fisherman_id', 'submitform_id');
    }

SubmitForm controller

$sf = new SubmitForm;
$sf->price_per_kg = $request->price_per_kg;
$sf->fisherman()->sync($request->fisherman, false);
if ($sf->save()) {
  return $this->responseSuccess("OK");
}

I want to insert many fisherman_id with the same submitform_id.

Ad

Answer

You've to save the fisherman model first. See below:

$sf = new SubmitForm;
$sf->price_per_kg = $request->price_per_kg;

if ($sf->save()) {
    $sf->fisherman()->sync($request->fisherman, false);

    return $this->responseSuccess("OK");
}

Hope it helps!

Ad
source: stackoverflow.com
Ad