I am using Laravel 5.1 and have a multi-tenancy database setup using a trait
and scope
as below. How can I add to this so that all insert queries also get the cust_id
parameter injected?
Scope:
<?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
{
/**
* Create a new filter instance.
*
* @param UsersRoles $roles
* @return void
*/
public function __construct()
{
$this->custId = Session::get('cust_id');
}
/**
* Apply scope on the query.
*
* @param Builder $builder
* @param Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
if($this->custId)
{
$builder->where($model->getTable() . '.cust_id', $this->custId);
}
else
{
$model = $builder->getModel();
$builder->whereNull($model->getKeyName());
}
}
/**
* Remove scope from the query.
*
* @param Builder $builder
* @param Model $model
* @return void
*/
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();
}
}
Trait:
<?php
namespace App\Scopes;
trait MultiTenantTrait
{
/**
* Boot the scope.
*
* @return void
*/
public static function bootMultiTenantTrait()
{
static::addGlobalScope(new MultiTenantScope());
}
/**
* Get all tenants.
*
* @return string
*/
public static function allTenants()
{
return (new static())->newQueryWithoutScope(new MultiTenantScope());
}
}