I’m creating a project in Laravel where each company has multiple departments. Each department has a certain number of locations, and each location has assigned devices.
To filter the results by company_id
, I created a global scope:
class CompanyScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
return $builder->where('company_id', auth()->user()->company_id);
}
}
When I try to run the following query, however, I get an error that the column company_id
is ambiguous:
Departments::withCount(['locations','devices'])->get();
Is there any way to add the table name to the scope condition to avoid this error?