I'm using a made up scenario, but facing similar issue.
I'm using Laravel 8 and have two models Family & Centre. Both containing common column name id.
In model Family I want to restrict families data based on centre of user logged in. For now I'm hardcoding it a dummy centre_id
Below is my booted function in Family model
protected static function booted()
{
static::addGlobalScope('user_access', function (Builder $builder) {
$builder->join('centres as c1', function ($join) {
$join->on('families.centre_id', '=', 'c1.id');
});
});
}
Now when I query Family model in a controller, it joins with Centre model and the id column of Family gets replaced with Centre model id column.
For eg:
Family has one row with id -> 100 and centre_id = 1 Centre has one row with id -> 1 and name = 'Test'
After join in booted function, I get value 1 in id when I query $family->id. $family is an instance of Family model.
Expected result : 100
I don't want to use select in booted function as there are many aggregated function I'm using which will be causing issues.