Last Updated: October 19, 2018
·
15.05K
· namklabs

Adding a table to your Laravel database

In the Terminal or command line, navigate to your Laravel installation. Then enter the following:

$ php artisan migrate:make <tablename plural>

...where <tablename plural> is the plural form of the name of your soon-to-be database table. So if your table is for user records then type users. Recommend you use lowercase and underscores only in your table name. Press enter to run the command (duh).

It should reply with:

Great! New migration created!

Cute. Now you will have a new file in your /application/migrations folder that will be your table name prefixed with a timestamp. Open it up. Inside the public function up(){ you need to put in the commands that will create the fields of your new table. These commands should be issued via the Schema Builder, and all you need to know is right here: http://laravel.com/docs/database/schema#adding-columns

The up() function defines how Artisan gets from one version of the database to the next. The down() functions defines how Artisan gets back to a previous version. Since you are creating your database for the first time in the up() function, it's easy to define the down() function: delete the table!

public function down(){
    Schema::drop('<same tablename>');
}

Next you need to run the migration to actually execute the up() function and have Laravel create the table. You can do this by entering the following:

$ php artisan migrate  

It will reply with:

Migrated/<filename>

Now check your database fool, your table has been created! :)

1 Response
Add your response

Some times when you are creating table in Laravel with migration, you might get error. In this case, check you MySQL version on the server. It should be at least 5.7.

over 1 year ago ·