1

I came from Django(Python) background and these days I'm working on a project which is based on Laravel(PHP).Do I have some option like generating database tables automatically?

Rajat Saxena
  • 3,834
  • 5
  • 45
  • 63

1 Answers1

8

Yes, using the Schema Builder and Migrations.

First you need to install the migrations table to the DB:

$ php artisan migrate:install

then create a migration

$ php artisan migrate:make create_users_table

this will create a PHP file in application/migrations. You may now edit it to have the settings you want, i.e.

<?php 

class Create_Users_Table
{

    public function up()
    {
        Schema::create('users', function($table)
        {
            $table->increments('id');
            $table->string('username');
            $table->string('email');
            $table->string('phone')->nullable();
            $table->text('about');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('users');
    }

}

and execute it using

$ php artisan migrate

Every time you change the database structure you'll have to create a new migration and execute it afterwards.

Say you want users to have a new column hometown instead of phone you'd create a new migration

$ php artistan migrate:make users_table_add_hometown

and edit the new file to contain

<?php 

class Users_Table_Add_Hometown
{

    public function up()
    {
        Schema::table('users', function($table)
        {
            $table->string('hometown');
            $table->drop_column('phone');
        });
    }

    public function down()
    {
        Schema::table('users', function($table)
        {
            $table->string('phone')->nullable();
            $table->drop_column('hometown');
        });
    }

}

You now have two migrations, one creating the table and one modifying it.

The artisan migrate command is smart enough to only execute migrations that are new to the system. So if a collegue of yours comes home after a long vacation and there were a few new migrations it will automatically only import the ones that were created after he left.

Nils Werner
  • 34,832
  • 7
  • 76
  • 98
  • One more thing.When there is some error in the definition of create table,the table gets created into database but that wont drop(I have to go to mysql to drop it manually) when I rollback the migration.Any Ideas? – Rajat Saxena Apr 21 '13 at 10:01
  • I have added the (not very well documented) ability of `up()` and `down()` migrations. – Nils Werner Apr 21 '13 at 10:14
  • Also, it is important that you do not remove the dates from the migration filenames. They decide the order in wich they are being executed. – Nils Werner Apr 21 '13 at 10:17
  • How do models fit into the picture here? – Julien Jan 30 '17 at 17:53