How to Create Table using Migration in Laravel 9

Creating Tables using Migration in Laravel 

1. Create table using php artisan make:migration create_table_name_table

for exmaple -

php artisan make:migration create_customers_table

2. Go to database>migrations>, open customers table file and add rows.

public function up()
    {
        Schema::create('customers', function (Blueprint $table) {
            $table->id('customer_id');     // customer_id
            $table->string('name', 60);
            $table->string('email', 100);
            $table->enum('gender', ['M', 'F', O])->nullable();
            $table->text('address');
            $table->date('dob')->nullable();
            $table->string('password');
            $table->boolean('status')->default(1);
            $table->integer('points')->default(0);
            $table->timestamps(); 
            // created_at updated_at these two by default feilds given by laravel
        });
    }

3. Add above created table in the database with these commands - php artisan migrate or php artisan migrate -force. 

php artisan migrate

4. If you want to delete table from database run this command - php artisan migrate:rollback.   

php artisan migrate:rollback

5. If you have make a relation between two or more tables and they are not connecting after running migrate then use - php artisan migrate:refresh this command delete all the tables and recreate them again.   

php artisan migrate:refresh

6. If you want to add new columns in the table use this command - php artisan make:migration add_columns_to_customers_table

php artisan make:migration add_columns_to_customers_table

* @return void
     */
    public function up()
    {
        Schema::table('customers', function (Blueprint $table) {
            $table->string('city', 50)->nullable()->after('address');
            $table->string('state', 50)->nullable()->after('address');
        });
    }

after completion run again - 

php artisan migrate
 to add these columns in the database.

Comments