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

pedroroccon's avatar

Laravel belongs to relation, but with a combination of fields

Greetings!

I'm developing a Laravel application with just 02 models. One is called Company and another is called Customer. I have a "belongsTo"relation between Customer and Company for each User. For example:

Each company has a code that is a combination os 03 columns in database: cnpj_base, cnpj_ordem and cnpj_dv. In my Customer database my relation poinst to the combination of this 03 columns. For example:

I have the company Lacacasts, which has the following code: cnpj_base = 1234 cnpj_ordem = 0000 cnpj_dv = 01

In my Customer database I have the following scenario: user_id = 4 company_code = 1234000001

How do I make a belongsTo relation in Customer model to link my Customer to the Company, like that?

$customer->company; // returns the company
0 likes
2 replies
hamzaaslam's avatar

To create a belongsTo relationship between the Customer and Company models based on the combination of the cnpj_base, cnpj_ordem, and cnpj_dv columns in the Company model, you can define the relationship in the Customer model as follows:

class Customer extends Model
{
    public function company()
    {
        return $this->belongsTo(Company::class, 'company_code', 'code');
    }
}

In the belongsTo method, the first argument is the related model name (Company::class), the second argument is the foreign key (company_code), and the third argument is the owner key (code).

Next, in the Company model, you can define an accessor to concatenate the cnpj_base, cnpj_ordem, and cnpj_dv columns into the code attribute:

class Company extends Model
{
    public function getCodeAttribute()
    {
        return $this->attributes['cnpj_base'] . str_pad($this->attributes['cnpj_ordem'], 4, '0', STR_PAD_LEFT) . $this->attributes['cnpj_dv'];
    }

    public function customers()
    {
        return $this->hasMany(Customer::class, 'company_code', 'code');
    }
}

In the getCodeAttribute method, we concatenate the cnpj_base, cnpj_ordem, and cnpj_dv columns into the code attribute.

Finally, you can retrieve the related Company model from a Customer instance as follows:

$customer = Customer::find(1);
$company = $customer->company;

This will return the Company model with the code attribute matching the company_code column in the Customer model.

Please or to participate in this conversation.