1 | <?php |
||
2 | |||
3 | namespace App\Console\Commands; |
||
4 | |||
5 | use App\Models\Tenant; |
||
6 | use Illuminate\Console\Command; |
||
7 | use Illuminate\Support\Facades\DB; |
||
8 | use Symfony\Component\Console\Exception\RuntimeException; |
||
9 | |||
10 | class CreateTenant extends Command |
||
11 | { |
||
12 | /** |
||
13 | * The name and signature of the console command. |
||
14 | * |
||
15 | * @var string |
||
16 | */ |
||
17 | protected $signature = 'tenant:create {subdomain : tenant subdomain}'; |
||
18 | |||
19 | /** |
||
20 | * The console command description. |
||
21 | * |
||
22 | * @var string |
||
23 | */ |
||
24 | protected $description = 'Creates new tenant with new database'; |
||
25 | |||
26 | /** |
||
27 | * Create a new command instance. |
||
28 | * |
||
29 | * @return void |
||
30 | */ |
||
31 | public function __construct() |
||
32 | { |
||
33 | parent::__construct(); |
||
34 | } |
||
35 | |||
36 | /** |
||
37 | * Execute the console command. |
||
38 | * |
||
39 | * @return mixed |
||
40 | */ |
||
41 | public function handle() |
||
42 | { |
||
43 | $subdomain = $this->argument('subdomain'); |
||
44 | |||
45 | if (!ctype_alnum($subdomain)) { |
||
46 | throw new RuntimeException('Subdomain can consist of alphanum chars only.'); |
||
47 | } |
||
48 | |||
49 | $num = Tenant::where('subdomain', $subdomain)->count(); |
||
50 | |||
51 | if ($num) { |
||
52 | throw new RuntimeException('Tenant with subdomain \''.$subdomain.'\' already exists.'); |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
53 | } |
||
54 | |||
55 | $tenant = new Tenant(); |
||
56 | $tenant->subdomain = $subdomain; |
||
57 | $tenant->save(); |
||
58 | |||
59 | $databaseName = 'tenant_'.$tenant->id; |
||
60 | DB::connection('tenant')->statement('CREATE DATABASE '.$databaseName); |
||
61 | |||
62 | $this->callSilent('tenant:migrate', [ |
||
63 | 'tenantId' => $tenant->id, |
||
64 | ]); |
||
65 | |||
66 | $this->info('Created tenant with subdomain \''.$subdomain.'\' and ID '.$tenant->id.'.'); |
||
67 | $this->info('Database tables has been migrated.'); |
||
68 | } |
||
69 | } |
||
70 |