It seems like you're trying to set up a form to handle addresses related to a Group model, and you want to ensure that the relationships between addresses, cities, states, and countries are properly managed. Here's how you can structure your models and handle the form inputs to ensure everything is connected correctly.
Model Setup
You already have the relationships set up in your models, which is great. Ensure that each model correctly defines its relationships:
// Group Model
public function addresses()
{
return $this->morphMany(Address::class, 'addressable');
}
// Address Model
public function country(): BelongsTo
{
return $this->belongsTo(Country::class, 'country_id');
}
public function state(): BelongsTo
{
return $this->belongsTo(State::class, 'state_id');
}
public function city(): BelongsTo
{
return $this->belongsTo(City::class, 'city_id');
}
Form Handling
When handling the form submission, you need to ensure that the address data is correctly associated with the Group. Here's a basic way to handle the form submission and save the data:
public function store(Request $request)
{
$group = Group::find($request->group_id); // Assuming you pass the group ID
$address = new Address([
'title' => $request->input('addresses.title'),
'address_1' => $request->input('addresses.address_1'),
'address_2' => $request->input('addresses.address_2'),
'city_id' => $request->input('addresses.city_id'),
'state_id' => $request->input('addresses.state_id'),
'country_id' => $request->input('addresses.country_id'),
'postal_code' => $request->input('addresses.zip'),
]);
$group->addresses()->save($address);
return redirect()->back()->with('success', 'Address added successfully!');
}
Handling City Input
For handling city input where the city is manually entered but should match an existing city in the database if available, you can modify the city handling like this:
$cityName = $request->input('addresses.city');
$stateId = $request->input('addresses.state_id');
$city = City::firstOrCreate([
'name' => $cityName,
'state_id' => $stateId
]);
$address->city_id = $city->id;
This code checks if a city with the given name and state ID exists, and if not, it creates a new city. This ensures that if a city is already in the database, it won't create a duplicate.
Conclusion
With this setup, you should be able to handle the creation of addresses linked to a group, with proper relationships to cities, states, and countries. Make sure to validate the inputs to ensure data integrity.