· 6 years ago · Jul 20, 2019, 09:48 AM
1<?php
2
3
4namespace App\Traits;
5
6
7use Illuminate\Support\Facades\DB;
8use Illuminate\Support\Facades\Schema;
9
10/**
11 * Trait MigrationHelper
12 * @package App\Traits
13 *
14 * @note examples
15 *
16 * database/migrations/add_index_column_example.php
17 *
18 * class AddIndexColumnExample extends Migration
19 * {
20 * use MigrationHelper;
21 *
22 * public function up()
23 * {
24 * $helper = $this;
25 *
26 * $helper->setForeignKeyChecks(false);
27 *
28 * Schema::table('sample_a_table', static function (Blueprint $table) use ($helper) {
29 *
30 * // Create index if it does not exists
31 * if (!$helper->hasIndex('table_name', 'index_name')) {
32 * $table->unique('user_id', 'index_name');
33 * }
34 *
35 * // Create column if it does not exists
36 * if (!$helper->hasColumn('table_name', 'column_name')) {
37 * $table->integer('column_name')->after('id');
38 * }
39 * });
40 *
41 * $helper->setForeignKeyChecks(true);
42 * }
43 * }
44 */
45trait MigrationHelper
46{
47 /**
48 * Switch Foreign Key Check
49 * @param bool $onOff
50 */
51 public function setForeignKeyChecks(bool $onOff): void
52 {
53 DB::statement('SET FOREIGN_KEY_CHECKS=' . (int)$onOff);
54 }
55
56 /**
57 * Check if the index exists in a table
58 * @param $table
59 * @param $index
60 * @return bool
61 */
62 public function hasIndex($table, $index): bool
63 {
64 return collect(DB::select(sprintf('SHOW INDEXES FROM %s', $table)))
65 ->pluck('Key_name')
66 ->contains($index);
67 }
68
69 /**
70 * Alias of Schema::hasColumn()
71 * @param $table
72 * @param $column
73 * @return bool
74 */
75 public function hasColumn($table, $column): bool
76 {
77 return Schema::hasColumn($table, $column);
78 }
79
80}