Create database tables in Laravel 5

1. Generate a migration script for creating a users table using artisan on command line. It will create a php file in database/migrations/yyyy_mm_dd_ssssss_create_posts_table.php

php artisan make:migration create_posts_table --create=posts

2. Open the file database/migrations/yyyy_mm_dd_ssssss_create_posts_table.php, it should look like this

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('posts');
    }
}

3. Update the file database/migrations/yyyy_mm_dd_ssssss_create_posts_table.php to add some more fields and foreign key.

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->index()->unsigned();
            $table->date('date')->index();
            $table->string('whats_done');
            $table->string('will_do');
            $table->timestamps();
            $table->foreign('user_id')
                  ->references('id')->on('users')
                  ->onDelete('cascade');  
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('posts');
    }
}

4. Generate a Post model using artisan on command line. It will create a model class in app/Post.php

php artisan make:model Post

5. Open up the file app/Post.php, you should see something similar to this.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    //
}

6. For adding more data types when creating a database table in Laravle’s migration script on step 3, take a look at this file vendor/laravel/framework/src/Illuminate/Database/Schema/Blueprint.php

Search within Codexpedia

Custom Search

Search the entire web

Custom Search