Laravel migration example - Create Table, check if has table or column and add forignkey

0

Laravel Migration Examples


Below is some examples (hasTable, hasColumn, create and alter table, migrate on specific migration file) to working with Laravel migration you may need it.

1. Check if has table

Schema::hasTable("table_name") // return bool

2. Check if has column

Schema::hasColumn("table_name", "column_name") // return bool

3. Create table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class TestAddTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if (!Schema::hasTable('staff')) {
            Schema::create('staff', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->unsignedBigInteger('fk_company');
                $table->string('name', 100);
                $table->string('email', 100);
                $table->tinyInteger('single')->default(0);
                $table->float('salary')->nullable();
                $table->timestamps();//created_at,updated_at

                $table->foreign('fk_company')->references('id')->on('companies'); //Add forignkey
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('table_staff');
    }
}

4. Alter table (Make change column structure)

Schema::table('staff', function (Blueprint $table) {
            $table->string('email', 100)->nullable()->change();
        });

5. Migrate on specific file 

php artisan migrate --path=database/migrations/migration.php
Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)

Random Posts