3 - Create Migrations

Laravel

We're going to create the models we need, and their migrations in one go. We need a Thread model and we need a Reply model. On your command line, type

php artisan make:model Thread -mr

The make:model bit creates the model, the m modifies creates the migration and the r modifier creates a resourceful controller. We'll look at the controller later, because for now we are interested only in the migration. Let's create a model and migration for replies:

php artisan make:model Reply -mc

Full CRUD functionality is not required for replies, so we specified a c modifier to create a (no resourceful) controller.

Looking in database/migrations, we can see migrations to create users and password resets tables. These two come by default with every Laravel installation. We should also see migrations to create threads and replies tables. These were generated by the two commands we have just run. We will now use these migrations to specify what columns will appear in each table.

Database Migrations

Open up the create_threads_table migration and amend the up() function like this:

    public function up()
    {
        Schema::create('threads', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }
					

In doing this we have added two new columns for title and body to the default columns for id, created_at timestamp and updated_at timestamp that you always get with a new migration. When we run the migration, all those columns will appear in the threads table with the attributes defined here. In a similar fashion, we will mow amend the create_replies_table migration like this:

    public function up()
    {
        Schema::create('replies', function (Blueprint $table) {
            $table->increments('id');
            $table->text('body');
            $table->timestamps();
        });
    }
					

The up() function runs when the migration is performed and the down() function runs when the migration is rolled back. You can see that the up() function creates the table and the down function drops it, so they are basically the opposite of each other.

Now we are ready to run the migrations. We do this by typing on the command line:

php artisan migrate

If all goes well, you should see something like this:

PHP Artisan Migrate

And looking in your myforum database in your database manager, you should see the new tables:

New Tables In phpMyAdmin

We have the foundations set. The next step is to set up some routes that will allow users to visit pages on our site.