How is your store URL ?
Adding foreign key to relationship model
Not sure if the title makes any sense but here is my question. I currently have a Family model and a Contact model. Once the Family is created I am trying to add contacts to the Family. The part that I am getting confused it how to tell the contact form that this new contact I am creating is related to a specific id in the Family model.
Currently I have a "Main" form that lets me insert family and contact data at once but I want the ability to add additional contacts to the model.
My routes are setup like the following:
Route::resource('families', 'FamiliesController');
Route::resource('families.contacts', 'ContactsController');
The form is currently at
/families/{id}/contacts/create/
My Models are setup like:
Family Model
public function contacts()
{
return $this->hasMany('App\Contact');
}
Contact Model
public function family()
{
return $this->belongsTo('App\Family');
}
I currently have the create route setup with the contact form being displayed, but once I submit the form I get a QueryException Error
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`billing_dev`.`contacts`, CONSTRAINT `contacts_family_id_foreign` FOREIGN KEY (`family_id`) REFERENCES `families` (`id`) ON DELETE CASCADE) (SQL: insert into `contacts` (`first_name`, `middle_name`, `last_name`, `relationship`, `address1`, `address2`, `city`, `state`, `zip`, `cell_phone`, `home_phone`, `work_phone`, `email`, `is_primary`, `updated_at`, `created_at`) values
I tried setting the family_id manually just to see if I could get it to work by adding the following to the store method:
$contact['family_id'] = 1;
but the idea failed me.
How do I go about grabbing the id which is in the URL "/families/1/contacts/create/" and assign that to the family_id field on the contacts Model.
I may be going about this the wrong way as I am still trying to learn Laravel.
Please or to participate in this conversation.