Laravel 5.1 Multitenancy setup

2019-07-15 01:23发布

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());
    }
}

1条回答
看我几分像从前
2楼-- · 2019-07-15 02:15

In order to do that, you'll need to override the default Eloquent Model's behaviour. You can modify one of the methods that participate in creating object or saving it.

My suggestion is to override the default creation behaviour logic as this will give you an object with custId set even before you save it to the database.

The easiest way to achieve that is to override the inherited constructor in a trait. In order to do that, add this method to your trait:

public function __construct(array $attributes = [])
{
  parent::__construct(array_merge($attributes, ['cust_id' => $this->custId]));
}
查看更多
登录 后发表回答