CreateRolesAndPermissionsTables::down()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 7
rs 10
c 1
b 0
f 0
1
<?php
2
3
use Helldar\Roles\Support\Database\BaseMigration;
4
use Illuminate\Database\Schema\Blueprint;
5
6
class CreateRolesAndPermissionsTables extends BaseMigration
7
{
8
    public function up()
9
    {
10
        $this->createTable($this->roles);
11
        $this->createTable($this->permissions);
12
13
        $this->createPivot($this->user_roles, $this->users, $this->roles, 'user_id', 'role_id');
14
        $this->createPivot($this->role_permissions, $this->roles, $this->permissions, 'role_id', 'permission_id');
15
    }
16
17
    public function down()
18
    {
19
        $this->schema()->disableForeignKeyConstraints();
20
21
        $this->dropTables($this->role_permissions, $this->user_roles, $this->permissions, $this->roles);
22
23
        $this->schema()->enableForeignKeyConstraints();
24
    }
25
26
    protected function createTable(string $table)
27
    {
28
        $this->create($table, function (Blueprint $table) {
29
            $table->bigIncrements('id');
30
            $table->string('name')->unique();
31
            $table->timestamps();
32
        });
33
    }
34
35
    protected function createPivot(string $table, string $first_table, string $second_table, string $first_key, string $second_key)
36
    {
37
        $this->create($table, function (Blueprint $table) use ($first_table, $second_table, $first_key, $second_key) {
38
            $table->unsignedBigInteger($first_key);
39
            $table->unsignedBigInteger($second_key);
40
41
            $table->foreign($first_key)->references('id')->on($first_table)->onDelete('cascade');
42
            $table->foreign($second_key)->references('id')->on($second_table)->onDelete('cascade');
43
44
            $table->primary([$first_key, $second_key]);
45
        });
46
    }
47
}
48