I want to insert data to one table (called Startups) which has 2 "BelongsTo" relations, I found how to do this with one table (One to Many) in a good Laravel's documentation but I'm beginner in this area and I don't know how to insert data to related to 2 different tables (Categories - Contacts) in one common table (Sturtups), to understand this better please see the image I attached below
Here is my code (please don't pay attention to Sessions, it doesn't matter in that case):
$category_id = Session::get('category_id');
$country_id = Session::get('country_id');
$new_contact = new Contact([
'name' => Session::get('contact_name'),
'phone' => Session::get('contact_phone'),
'email' => Session::get('contact_email')
]);
$country = Country::find($country_id);
$country->contacts()->save($new_contact);
$new_startup = new Startup([
'name' => Session::get('startup_name'),
'description' => Session::get('startup_description'),
'url' => Session::get('startup_url'),
'logo' => Session::get('logo_name')
]);
$category = Category::find($category_id);
$category->startups()->save($new_startup);
$contact = Contact::find( $country->contacts()->id );
$contact->startups()->save($new_startup);
Database Relations image: image of relations between tables in the DB
Additional info: I have this error: "General error: 1364 Field 'contact_id' doesn't have a default value" I know why that error happens (I'm trying to create Startup without id of contact)
I just want to know how insert data in that case
Thank you guys for any help!
Answer to your question is:
make that field nullable in database migration so this error will not occur
$table->unsignedInteger('contact_id')->nullable();