menu

Questions & Answers

Occasionally Laravel firstOrCreate results in 0 id value and results in Integrity constraint violation: 1452 Cannot add or update a child row

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.

Comments:
2023-01-19 23:30:06
@RiggsFolly when I checked the database the parent row does exist. I am not sure why can't it find.
2023-01-19 23:30:06
mind sharing the relation code ? ->addresses()
2023-01-19 23:30:06
@N69S added code as requested
2023-01-19 23:30:06
I think before 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.
2023-01-19 23:30:06
Do you have a mutator on Customer::class named getIdAttribute() ?
Answers(0) :