I have a global setting in Laravel 5.1, which works fine. However, on some of my pages I use MySQL joins using the Eloquent constructor. This leads to an ambiguous error:
Column 'cust_id' in where clause is ambiguous
I am not sure how to avoid this problem. I know that I can use subqueries instead, but is there another solution?
Here is my scope file:
<?php namespace App\Scopes; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\ScopeInterface; use App\Customers; use DB, Session; class MultiTenantScope implements ScopeInterface { public function __construct() { $this->custId = Session::get('cust_id'); } public function apply(Builder $builder, Model $model) { if($this->custId) { $builder->whereCustId($this->custId); } else { $model = $builder->getModel(); $builder->whereNull($model->getKeyName()); } } public function remove(Builder $builder, Model $model) { $query = $builder->getQuery(); $query->wheres = collect($query->wheres)->reject(function ($where) { return ($where['column'] == 'cust_id'); })->values()->all(); } }
source share