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

pulkitdhaka52's avatar

laravel: Can not create relation in model using foreign key and non-primary key

We are getting an issue in creating the relationship inside the laravel model.

Requirement: We want to create a relation in such a way that we have three tables

block_primary_table

|block_id | block_name | | -------- | ----------- | | 1 | XYZ | | 2 | ABC |

block_translation_table

| id | language_id | block_id | block_name | | - | ------------ | --------- | ------------ | | 1 | 1 | 1 | XYZ-English | | 1 | 2 | 1 | XYZ-Hindi | | 1 | 1 | 2 | ABC-English | | 1 | 2 | 2 | ABC-Hindi |

and third table for a user, where we capture the user area user_area

| user_id | user_name | district | block | | ------- | ----------- | ------ | ----- | | 1 | ABC-user| 1 | 1 |

and we have a form for a module where we have a district and block field the block field is dependent on the district field, so while creating a new entry the block is loaded into the dropdown depending upon district value so that we can show the value easily because it will be handled by an ajax.

but during the edit operation, suppose we are editing user_id 1 from user_area that time existing value needs to come into the form, but here the issue like other fields value comes correctly, but for the block, during edit operation, the value comes up to field using entity, that is defined in the model, so in that relationship we have

//relationship with block translation table
public function blockRelation() {
     return $this->belongsTo(blockTranslation::class, 'block','block_id');
}

so, we are expecting that it will return the value from the block translation table by mapping the block(foreign key of user_area) with block_id(non-primary key of block_translation_table) of block_translation_table.

we are column name in relation still it is mapping block column of user_area table with id column of block_translation_table.

So please provide the solution for the issue, like how can we create the relationship in the laravel model for foreign key and non-primary key.

0 likes
2 replies

Please or to participate in this conversation.