Now we will create something with Laravel, first thing we have to do is setup database. After that we will try to create table using migration. To achieve that, there are 2 methods to setting up details for our database setting.

  • .env file (located in root of project/.env)
  • database.php (located in root of project/config/database.php)

Setup through .env file

.env file is created only in freshly installed. This file doesn’t appear when you deploy it. If we want to deploy .env file along, then we have to remove .env in list of .gitignore file. By default .env file come along in list of .gitignore, because it contains sensible information.

If we open .env file, it looks like this.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=sampleLaravel
DB_USERNAME=root
DB_PASSWORD=

Then we are free to change setting as we like.

Setup through database.php file

For second method, we set detail information database from database.php file under config/ sub-directory.


'default' => env('DB_CONNECTION', 'mysql'),

    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections setup for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */

    'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
        ],

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'sampleLaravel'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],

        'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'schema' => 'public',
        ],

    ],

As default, for connection method set into mysql. If we want to use the other database connection we simply change on line 29 from the image above to connection method we want.

This is how to setup database in Laravel, looks extremely simple. Next we will create table using migration.

Migration process

In short, migration are files which contain class definition with both up() and down() methods. The up() method is run when migration executed to apply changes of database. The down() method is run to revert changes. When we need to update database tables, we just need to create new migration.

For starting, create database from PHPMyAdmin or whatever database management tool that you are using. Here we will use PHPMyAdmin.

db

Then choose method to setup database connection like we have discussed above. After done with setup database, we were ready for migration process of database. Now run command to begin migration process. php artisan make:migration your-class-migration-name

db1

Make sure file for migration has been created, check under /database/migration subdirectory.

db2

Open migration file that freshly created, and it looks like this.


<?php

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

class Sampletable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

As suggestion when create migration file, make sure use name of file with descriptive name, so it’s clear what migration does from just a glance. Now we will create table scheme for database programmatically. Remember when create tables, write schemas of table in up() method. For my setup it will look like this.

/**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        /** for documentation of Blueprint
        * @see  offline:    root project\vendor\laravel\framework\src\Illuminate\Database\Schema\Buleprint.php
        * @see  online:     https://laravel.com/api/5.2/Illuminate/Database/Schema/Blueprint.html
        */
        Schema::create('people', function (Blueprint $table) {
            $table->increments('id');
            $table->string('firstname');
            $table->string('lastname');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
        
    }

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

For my setup schemas, I create Id for auto-increment and automatically is going to set as primary key from Laravel. Firstname, lastname, email and password in VARCHAR type columns, and adding email as unique to prevent have two same records in table. The rememberToken() will create VARCHAR type column for security reason and will be used to store token “remember me” sessions. The timestamps() will automatically create two time stamp fields namely created_at and updated_at.

Done with setup table schema, now time to process migration process to generate SQL into table. To do that, type command php artisan migrate. If process getting error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES). Check .env file, make sure values set into right settings.

db3

If successfully executed, in PHPMyAdmin there will be 3 tables as many as migration files.

db4

The migrations table created by default to doing job when php artisan migrate:rollback executed.

That’s it for database setup, for references  see previous post Laravel App Structure. Next we will talk about Routing.

command3

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s