PHP code example of aloisogomes / laravel-db-tenant
1. Go to this page and download the library: Download aloisogomes/laravel-db-tenant 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/ */
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use AloisoGomes\LaravelDbTenant\Traits\HasTenantConnection;
class User extends Model
{
use HasTenantConnection;
// ...
}
use AloisoGomes\LaravelDbTenant\Facades\Tenant;
use App\Models\User;
// 1. Default Context (uses default connection from .env), in our example connection named as 'default'
$defaultUser = User::find(1);
// 2. Switch to 'legacy' connection
Tenant::start('legacy');
$legacyUser = User::find(1);
// This query runs on 'lagacy'
// 3. End context (returns to previous state)
Tenant::end();
Tenant::start('legacy');
$legacyUser = User::find(500);
Tenant::end();
// We are back to the default connection here
$defaultUser = User::find(1);
// UPDATE TEST:
$defaultUser->update(['name' => 'Local']); // Updates default DB
$legacyUser->update(['name' => 'Legacy']); // Updates 'legacy' automatically!
Tenant::start('legacy');
// Forces 'default' connection even inside the 'lagacy' block
$admin = User::tenant('default')->find(1);
Tenant::start('legacy');
Tenant::transaction(function () {
// This transaction starts specifically on 'legacy' connection
$user = User::find(1);
$user->balance -= 100;
$user->save();
// If this fails, only 'legacy' is rolled back
});
Tenant::end();
// Emergency reset
Tenant::reset();
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.