Skip to content

Basic & Advanced Concepts on Laravel Database Migrations & Models

Creating Migration File:

php artisan make:migration create_[table_name]_table --table=[table_name]

Example:

php artisan make:migration create_users_table --table=users

Migration File for Updating Table:

php artisan make:migration add_columns_to_users_table --table=users

Example of a Migration File:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name', 64); /* second parameter defines length of a varchar field, it is optional */
        $table->string('email')->unique(); /* unique() makes the field unique */ 
        $table->timestamp('email_verified_at')->nullable(); /* nullable() makes the field accept null values */
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

Defining a Foreign Key:

public function up()
{
    Schema::create('items', function (Blueprint $table) {
        $table->string('code', 8)->primary(); /* set as primary key manually */
        $table->string('description')->unique();
        $table->string('brand_code', 8);
        $table->string('uom', 3)->default('PC'); /* set a default value */
        $table->boolean('is_active')->default(true);
        $table->timestamps();

        $table->foreign('brand_code')->references('code')->on('brands'); /* defines brand_code as a foreign key to brands table */
    });
}

Defining a Self Referencing Foreign Key:

public function up()
{
    Schema::create('entities', function (Blueprint $table) {
        $table->string('code', 12)->primary();
        $table->string('description')->unique();
        $table->string('parent')->nullable();
        $table->boolean('is_active')->default(true);
        $table->timestamps();
    });

    /**
     * Define the parent as self referencing key after the table is created
     */
    Schema::table('entities', function (Blueprint $table){
        $table->foreign('parent')->references('code')->on('entities')->onUpdate('cascade')->onDelete('restrict');
    });
}

Leave a Reply

Your email address will not be published. Required fields are marked *