Skip to content

Latest commit

 

History

History
executable file
·
336 lines (250 loc) · 8.71 KB

README.md

File metadata and controls

executable file
·
336 lines (250 loc) · 8.71 KB

Laravel Multi-Tenant

Sep 29, 2014: WIP for release as an L4 package.

Installation

  1. Require this package in your composer.json file in the "require" block:

    "globecode/laravel-multitenant": "dev-master"
  2. Add the service provider to the providers array in app/config/app.php. This is only used for the "Publish config" command two steps down:

    'GlobeCode\LaravelMultiTenant\LaravelMultiTenantServiceProvider'
  3. cd into your project directory and update via Composer:

    composer update
  4. Publish the config to your application. This allows you to change the name of the Tenant column name in your schema. A config file will be installed to app/config/packages/globecode/laravel-multitenant/ which you can edit:

    php artisan config:publish globecode/laravel-multitenant
  5. Create and run new migrations to setup the necessary schema. Example migrations are provided in the Package migrations folder.

  6. Add the getTenantId() method to your User (and any other "scoped" models) or just once in a BaseModel (recommended):

    /**
     * Get the value to scope the "tenant id" with.
     *
     * @return string
     */
    public function getTenantId()
    {
        return (isset($this->tenant_id)) ? $this->tenant_id : null;
    }
  7. Optional Global Override. If you want to globally override scope, such as for an Admin, then add the isAdmin() method to your User model. The ScopedByTenant trait will look for this method and automatically override the scope on all queries if this method returns true:

    /**
     * Does the current user have an 'admin' role?
     *
     * @return bool
     */
    public function isAdmin()
    {
        // Change to return true using whatever
        // roles/permissions you use in your app.
        return $this->hasRole('admin');
    }

Usage

  1. Scope a model using the ScopedByTenant trait to make all queries on that model globally scoped to a Tenant. Never worry about accidentally querying outside a Tenant's data!

    <?php namespace Acme;
    
    use GlobeCode\LaravelMultiTenant\ScopedByTenant;
    
    class Example {
    
        /**
         * Only this line is required. The extra below is just
         * for example on what a relation might look like.
         */
        use ScopedByTenant;
    
        protected $table = 'example';
    
        /**
         * Query the Tenant the Example belongs to.
         *
         * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
         */
        public function tenant()
        {
            return $this->belongsTo('Acme\Tenant');
        }
    }
  2. Globally removing scope:

    A: Globally remove scope from a Controller, such as in an Admin situation:

    <?php
    
    use GlobeCode\LaravelMultiTenant\ScopedByTenant;
    
    class AdminExamplesController {
    
        /**
         * @var Acme\Repositories\ExampleRepository
         */
        protected $exampleRepo;
    
        public function __construct(ExampleRepository $exampleRepo)
        {
            $this->exampleRepo = $exampleRepo;
    
            // All queries in this controller on 'exampleRepo'
            // will be 'global' and not scoped.
            $this->exampleRepo->removeTenant();
        }
    
        /**
         * Display a listing of all Examples.
         *
         * @return Response
         */
        public function index()
        {
            // Global, will *not* be scoped.
            $leads = $this->exampleRepo->getAll();
    
            $this->view('examples.index', compact('examples'));
        }
    }

    Or

    B: Globally remove scope by using the Auth check in the ScopedByTenant trait's bootTenantId() method. See the instructions in the Setup -> Optional Global Override section above.

Note: You can use any of the public methods on the ScopedByTenant trait in your models and controllers.

Repositories

If you use repositories, you will need to build queries off of the TenantScope class instead of the ScopedByTenant trait. If you look at the TenantScope class you will see there are extensions to \Illuminate\Database\Query\Builder, these are methods available to your repositories; the trait won't work in repos.

Here is an example Eloquent repository with all the necessary methods for scoping. These methods should go in an EloquentBaseRepository class, to keep things DRY.

<?php namespace Acme\Repositories;

use Illuminate\Database\Eloquent\Model;

use Acme\Example;
use Acme\Repositories\ExampleRepository

class EloquentExampleRepository extends ExampleRepository {

    /**
     * @var Example
     */
    protected $model;

    /**
     * Method extensions from TenantScope class
     */
    protected $whereTenant;
    protected $applyTenant;
    protected $removeTenant;

    public function __construct(Example $model)
    {
        $this->model = $model;

        $this->whereTenant = null;
        $this->applyTenant = null;
        $this->removeTenant = false;
    }

    /**
     * Example get all using scope.
     */
    public function getAll()
    {
        return $this->getQueryBuilder()->get();
    }

    /**
     * Example get by id using scope.
     */
    public function getById($id)
    {
        return $this->getQueryBuilder()->find((int) $id);
    }

    /**
     * Limit scope to specific Tenant
     * Local method on repo, not on TenantScope.
     *
     * @param  integer  $id
     */
    public function whereTenant($id)
    {
        $this->whereTenant = $id;

        return $this;
    }

    /**
     * Remove Tenant scope.
     */
    public function removeTenant()
    {
        $this->removeTenant = true;

        return $this;
    }

    /**
     * Limit scope to specific Tenant(s)
     *
     * @param  int|array $arg
     */
    public function applyTenant($arg)
    {
        $this->applyTenant = $arg;

        return $this;
    }

    /**
     * Expand scope to all Tenants.
     */
    public function allTenants()
    {
        return $this->removeTenant();
    }

    protected function getQualifiedTenantColumn()
    {
        $tenantColumn = Config::get('laravel-multitenant::tenant_column');

        return $this->model->getTable() .'.'. $tenantColumn;
    }

    /**
     * Returns a Builder instance for use in constructing
     * a query, honoring the current filters. Resets the
     * filters, ready for the next query.
     *
     * Example usage:
     * $result = $this->getQueryBuilder()->find($id);
     *
     * @return \Illuminate\Database\Query\Builder
     */
    protected function getQueryBuilder()
    {
        $modelClass = $this->model;

        $builder = with(new $modelClass)->newQuery();

        if ( ! is_null($this->whereTenant))
            $builder->where($this->getQualifiedTenantColumn(), $this->whereTenant);

        if ($this->applyTenant)
            $builder->applyTenant($this->applyTenant);

        if ($this->removeTenant)
            $builder->removeTenant();

        $this->whereTenant = null;
        $this->applyTenant = null;
        $this->removeTenant = null;

        return $builder;
    }
}

Seeding

You can manually override the scoping in your seed files to avoid difficult lookups for relations, by setting the override manually:

<?php

use Acme\User;

use GlobeCode\LaravelMultiTenant\TenantScope;

class UsersTableSeeder extends DatabaseSeeder {

    public function run()
    {
        // Manually override tenant scoping.
        TenantScope::setOverride();

        User::create([
            'id' => 1,
            'tenant_id' => null, // an admin
            'email' => '[email protected]',
            'password' => 'secret',

            'created_at' => time(),
            'updated_at' => time()
        ]);

        User::create([
            'id' => 2,
            'tenant_id' => 1000, // a tenant
            'email' => '[email protected]',
            'password' => 'secret',

            'created_at' => time(),
            'updated_at' => time()
        ]);

        ...
    }
}

Note: set the tenant_id field (or whatever name you chose for the scoping column) on your User model to null for any in-house staff/admins.

About

Conception: Hard fork off AuraEQ Laravel Multi Tenant. Many thanks to him for the initial work.

Packagist: globecode/laravel-multitenant

Hashtag: #laravel-multitenant

Twitter: @jhaurawachsman

Copyright (c) 2014 Jhaura Wachsman

Licensed under MIT.