Creating data tables using migrations and schemas with laravel

Using Laravel, we can easily create our data model using schemas and migrations. In this
recipe, we’ll see some basic functionality of how Laravel accomplishes this.

Getting ready

For this recipe, we need a standard Laravel installation, as well as a MySQL database
configured in our database config file.

How to do it…

To complete this recipe, follow these steps:
1. Install our migrations table from the command prompt, using artisan:
php artisan migrate:install
2. Create a migration to hold our Schema code for creating a new table:
php artisan migrate:make create_shows_table
3. In our app/database/migrations directory, locate the file that should be named
similar to 2012_01_01_222551_create_shows_table.php. Add the schema to
create our table and add the columns:
class CreateShowsTable extends Migration {
/**
* Make changes to the database.
*
* @return void
*/
public function up()
{

Schema::create(‘shows’, function($table)
{
$table->increments(‘id’);
$table->string(‘name’, 140);
$table->integer(‘rating’)->nullable();
$table->timestamps();
});
}
/**
* Revert the changes to the database.
*

* @return void
*/
public function down()
{
Schema::drop(‘shows’);
}
}

4. Run the migration to add the table to the database, using the following command:
php artisan migrate
5. Create another migration so we can add a column to our table:
php artisan migrate:make add_actor_to_shows_table
6. In the app/database/migrations directory, find the file that has a name similar
to 2012_01_01_222551_add_actor_to_shows_table.php. Add the column to
our schema:
class AddActorToShowsTable extends Migration {
/**
* Make changes to the database.
*
* @return void
*/
public function up()
{
Schema::table(‘shows’, function($table)
{
$table->string(‘actor’)->nullable();
});
}
/**
* Revert the changes to the database.
*
* @return void
*/
public function down()
{
Schema::table(‘shows’, function($table)
{
$table->drop_column(‘actor’);
});
}

7. Run the migration in the command prompt to add the column to our table:
php artisan migrate

how its works…

Using Laravel’s Artisan command-line tool, we run the command to create a migrations table.
This will track any migrations and schema changes we make. Then we use Artisan to create a
migrations file that will hold the schema for our shows table.
In the shows schema, we create a simple table to hold a list of TV shows, and how we rate
them. The name of the show is set as a string, the rating as an integer, and we use Laravel’s
default mechanism for creating timestamps. When we run the migration, our table will be
created for us.
If we decide we want to add another column in our table, we just create another migration
file using Artisan. In this case, we’ll be adding a column to hold an actor’s name. Our schema
will get the table we already created and add

Leave a Reply

Your email address will not be published. Required fields are marked *