Kevin Kevin - 6 months ago 13
SQL Question

Creating records in multiple models from one form with eloquent

I have a form that captures users details and wish to save into two separate models: contacts and contract_addresses.

Below is the output from my

$request->all()
from within the controller method:

{
"first_name": "Joe",
"last_name": "Jackson",
"nickname": "JJ",
"salutation": "Mr",
"contact_address": {
"phone_mobile": "123456789",
"email": "jj@jackson.com",
"address_1": "123 Office",
"postcode": "2334",
"address_2": "456 Lane",
"province": "New Portia",
"city": "Okalaville",
"country": "Golubia"
}
}


I have set up appropriate relationships in my models as follows:

Contact Model:

public function address()
{
return $this->hasOne('App\Contact_address');
}


Contact_Address Model:

public function contact()
{
return $this->belongsTo('App\Contact');
}


Controller Method:
Here's how I have setup the controller method:

public function store(Request $request)
{
$contact = new Contact($request->except("contact_address"));
$contact_address = new Contact_address($request->contact_address);
$contact->setRelation('address', $contact_address);
$contact->push();
return back();
}


Errors with push(): The
push()
above throws 2 SQL exceptions:

1/2 PDOException in Connection.php line 408:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`myappdb`.`contact_addresses`, CONSTRAINT `contact_addresses_contact_id_foreign` FOREIGN KEY (`contact_id`) REFERENCES `contacts` (`id`))


2/2 QueryException in Connection.php line 673:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`myappdb`.`contact_addresses`, CONSTRAINT `contact_addresses_contact_id_foreign` FOREIGN KEY (`contact_id`) REFERENCES `contacts` (`id`)) (SQL: insert into `contact_address` (`phone_mobile`, `email`, `address_1`, `postcode`, `address_2`, `province`, `city`, `country`, `updated_at`, `created_at`) values (343434, , , , , , , , 2016-05-08 23:53:02, 2016-05-08 23:53:02))


I suspect that the problem seems to be that foreign key for the
contact.id
is not being passed through when performing the SQL insert for the addresses, even though the contact itself does get inserted into contacts table successfully.

How can I create a new record in both tables?


  • Do I have to create the contact, retrieve the contact.id, then use that again to save the addresses?

  • Is it better to remove sql foreign key constraint in my db?

  • How would you structure this?


Answer

Use save method.

public function store(Request  $request) { 
 $contact = Contact::create($request->except(["contact_address"]));
 $contact_address = new Contact_address($request->get('contact_address'));
 $contact->contact_address()->save($contact_address); 
 return back();
}
Comments