Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GodziLaravel's avatar

How to update a column using another table's column ?

Hello ,

I want to update CompanyAddresses.country_id using countries table, this update is based on CompanyAddresses.country and countries.code match.

CompanyAddresses

| id | country | country_id |
|----|---------|------------|
| 1  | BE      | null       |
| 2  | US      | null       |
| 3  | NL      | null       |

countries

| id | code | name          |
|----|------|---------------|
| 1  | BE   | Belgium       |
| 2  | US   | United States |
| 3  | NL   | Netherlands   |

I have Country and CompanyAddress models

Thanks!

0 likes
1 reply
bait-dept's avatar

I believe something like this would point you in the right direction.

Countries::all()->each(function($country){
    CompanyAddress::where('country', 'like', $country->code)->update([
        'country_id' => $country->id,
    ]);
});

Please or to participate in this conversation.