Laravel's migration system is very simple and easy to use. In this blog post, we'll show you
How to create a migration and run it on your database.
First, let's create a new migration:
php artisan make:migration create_users_table
This will create a new migration file in your database/migrations
directory. Open the newly created file and you'll see that it contains a up
and down
method. These methods are used to run the migration on your database.
In the up
method, we'll add a create
statement for our users
table:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Notice that we're using the Schema
facade to access the database schema builder. We can use the create
method to create a new table. The first argument is the name of the table, and the second argument is a closure that defines the columns in the table.
In the down
method, we'll add a drop
statement for our users
table:
public function down()
{
Schema::drop('users');
}
This will drop the users
table from your database when you rollback the migration.
Now that our migration is defined, we can run it on our database:
php artisan migrate
This will run all of your outstanding migrations.
You can also specify a specific migration to run:
php artisan migrate:specific create_users_table
Now that our users
table has been created, we can start adding data to it!