How To Create Table Using Command WIth Example In Laravel

admin_img Posted By Bajarangi soft , Posted On 23-09-2020

To create a new database table, use the create method on the Schema facade. The create method accepts two arguments: the first is the name of the table, while the second is a Closure which receives a Blueprint object .

How to Create Table in Laravel using command

Defining the new table:

Schema::create('users', function (Blueprint $table) {
$table->increments('id);
$table->string('name'); 
});
 

Checking For Table / Column Existence: You may check for the existence of a table or column using the  has Table and   hasColumn methods:

if (Schema::hasTable('users')) {
//
}

if (Schema::hasColumn('users', 'email')) {
//
}
 

Database Connection & Table Options: To perform a schema operation on a database connection that is not your default connection, use the connection method:

Schema::connection('foo')->create('users', function (Blueprint $table) {
$table->increments('id);
$table->string('name');
});

 
commands on the schema builder to define the table's options:

Command Description
$table->engine = 'InnoDB'; Specify the table storage engine (MySQL).
$table->charset = 'utf8mb4'; Specify a default character set for the table (MySQL).
$table->collation = 'utf8mb4_unicode_ci'; Specify a default collation for the table (MySQL).
$table->temporary(); Create a temporary table (except SQL Server).
 

Renaming / Dropping Tables:To rename an existing database table, use the rename method:

Schema::rename($from, $to);

To drop an existing table, you may use the drop or dropIfExists methods:

Schema::drop('users');

Schema::dropIfExists('users');
 

Renaming Tables With Foreign Keys: Before renaming a table, you should verify that any foreign key constraints on the table have an explicit name in your migration files instead of letting Laravel assign a convention based name. Otherwise, the foreign key constraint name will refer to the old table name.

For Example(1) implement  blueprint of table in migration folder as below 

<?php

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

class CreateDemosTable extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('demos', function (Blueprint $table) {
            $table->increments('id');
            $table->text('name');
            $table->text('desc');
            $table->timestamps();
            $table->softDeletes();
        });
    }

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

run command php artisan migrate in command prompt to see created table in database.

Related Post