PHP code example of solutosoft / laravel-multitenant

1. Go to this page and download the library: Download solutosoft/laravel-multitenant library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

solutosoft / laravel-multitenant example snippets


/**
 * Run the migrations.
 *
 * @return void
  */
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('firstName');
        $table->string('lastName');
        $table->string('login')->nullable();
        $table->string('password')->nullable();
        $table->string('remember_token')->nullable();
        $table->string('active');
        $table->integer('tenant_id')->nullable(true);
    });

    $Schema::create('pets', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('tenant_id');
    });
}




use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Solutosoft\MultiTenant\MultiTenant;
use Solutosoft\MultiTenant\Tenant;

class User extends Model implements Tenant
{
    use MultiTenant, Authenticatable;

    /**
     * @inheritdoc
     */
    public function getTenantId()
    {
        return $this->tenant_id;
    }

    ...
}

class Pet extends Model
{

  use MultiTenant;

  ...

}


// It's necessary will be logged in

$users = App\User::where('active', 1)->get();
// select * from `users` where `active` = 1 and tenant_id = 1

$pet = Pet::create(['name' => 'Bob']);
// insert into `pet` (`name`, 'tenant_id') values ('Bob', 1)




namespace App\Providers;

use Illuminate\Auth\EloquentUserProvider;
use Solutosoft\MultiTenant\TenantScope;

class TenantUserProvider extends EloquentUserProvider
{

    protected function newModelQuery($model = null)
    {
        return parent::newModelQuery($model)->withoutGlobalScope(TenantScope::class);
    }

}




namespace App\Providers;

class AuthServiceProvider extends ServiceProvider
{
    ...

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        ...

        Auth::provider('multitenant', function($app, $config) {
            return new TenantUserProvider($app['hash'], $config['model']);
        });
    }
}


return [
    ....
    'providers' => [
        'users' => [
            'driver' => 'multitenant',
            'model' => App\Models\User::class,
        ],
    ],

    ...