I have below code:
Job file
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
try {
$address = $this->setupCustomer();
} catch (\Exception $exception) {
throw $exception;
}
}
protected function setupCustomer(): CustomerAddress
{
$customer = Customer::firstOrCreate(
[
'email' => $this->transactionDetails['email'],
],
[
'first_name' => $this->transactionDetails['first_name'],
'last_name' => $this->transactionDetails['last_name'],
'phone' => $this->transactionDetails['phone'] ?? '',
]
);
return $customer->addAddress([
'street_address' => $this->transactionDetails['delivery_address']['address'],
'street_address2' => $this->transactionDetails['delivery_address']['address2'],
'postal_code' => $this->transactionDetails['delivery_address']['post_code'],
'city' => $this->transactionDetails['delivery_address']['city'],
'region' => $this->transactionDetails['delivery_address']['region'],
'country' => $this->transactionDetails['delivery_address']['country'],
]);
}
Customer.php Model
public function addAddress(array $address): CustomerAddress
{
$countryId = optional(Country::byCountryCode($address['country'])
->first())
->id;
$address = $this->addresses()->firstOrCreate([
'country_id' => $countryId ?? 0,
'street_address' => $address['street_address'],
'street_address2' => $address['street_address2'] ?? null,
'post_code' => $address['postal_code'],
'city' => $address['city'],
'region' => $address['region'],
]);
return $address;
}
/**
* Customer can have many addresses.
*
* @return HasMany
*/
public function addresses()
{
return $this->hasMany(CustomerAddress::class);
}
Occasionally, I get below error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`tbps`.`customer_addresses`, CONSTRAINT `customer_addresses_customer_id_foreign` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`)) (SQL: insert into `customer_addresses` (`country_id`, `street_address`, `street_address2`, `post_code`, `city`, `region`, `customer_id`, `updated_at`, `created_at`) values (<country_id>, <street_address>, ?, <post_code>, <city>, ?, 0, <timestamp>, <timestamp>))
Why does it end up with the customer_id = 0 in the sql statement? The customer is always created in the database, I am unable to replicate as it occurs occasionally.
->addresses()
return $customer->addAddress([ ...
best to add a checker if $customer is really exists/created ? or at least check if $customer->id > 0 ... just an extra precaution. getIdAttribute()
?