Use Laravel scope to be clear

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?

Yes, you can add the table name to the where clause in the global scope to avoid the error. Here’s the modified apply method:

public function apply(Builder $builder, Model $model)
{
    $table = $model->getTable();
    return $builder->where("$table.company_id", auth()->user()->company_id);
}

This will add the table name to the company_id column in the where clause, making it unambiguous.