menu

Laravel - RESTful project (API update data)



Pada tutorial sebelumnya kita sudah membuat API untuk show data, tutorial kali ini kita akan meneruskan sistem RESTful membuat API update data. Pada API ini kita akan melemparkan parameter ID yang mrupakan ID data yang akan di edit datanya.

Oke langsung saja kita mulai experimentnya,
Pertama, buat terlebih dahulu route APInya dengan cara edit file api.php pada path protected/app/routes/ menjadi seperti ini,
<?php 

//////////
// CRUD //
//////////
//pahamilah group route dibawah
Route::group(array('prefix' => 'crud'), function(){
 Route::get('users', 'Controller\Api\UserController@getUsers');
 Route::post('store-user', 'Controller\Api\UserController@storeUser');
 Route::get('{id}', 'Controller\Api\UserController@showUser');
 Route::patch('{id}', 'Controller\Api\UserController@updateUser');
});
Dapat dilihat pada code diatas, RESTful untuk update data menggunakan method PATCH.

Selanjutnya, buat method untuk update atau edit dengan cara edit file UserController.php pada path protected/app/controllers/api/ menjadi seperti ini,
<?php namespace Controller\Api;

use Model\User;
use \Response;
use \Validator;
use \Input;
use Illuminate\Http\Request;


class UserController extends \BaseController 
{
 public function getUsers()
 {
  $users = User::get();

  $response['status'] = 'OK';
  $response['result'] = $users;

  return Response::json($response);
 }

 public function storeUser()
 {
  $validator = Validator::make(
   Input::all(),
   array(
    "name"     => "required",
    "username"    => "required|unique:users,username",
    "email"     => "required|email|unique:users,email",
       "password"              => "required|min:6",
   )
  );
  // dd($_POST);
  if ($validator->passes()) {
      $user = User::storeOrUpdateUser(Input::all(), null);
      // dd($_POST);
      $response['status'] = 'OK';
      $response['result'] = $user;
     }
     else {
      $response['status'] = 'ERROR';
      $response['message'] = $validator->messages();
     }

  return Response::json($response);
 }

 public function showUser($id)
 {
  $user = User::find($id);

  if ($user) {
   $response['status'] = 'OK';
   $response['result'] = $user;
  } else {
   $response['status'] = 'ERROR';
   $response['message'] = 'User not found';
  }

  return Response::json($response);
 }

 public function updateUser($id)
 {
  $validator = Validator::make(
   Input::all(),
   array(
    "name"     => "required",
    "username"    => "required|unique:users,username,".$id,
    "email"     => "required|email|unique:users,email,".$id,
       "password"              => "required|min:6",
   )
  );

  $user = User::find($id); 

  if ($user) {
   if ($validator->passes()) {
       $user = User::storeOrUpdateUser(Input::all(), $user);
       $response['status'] = 'OK';
       $response['result'] = $user;
      }
      else {
       $response['status'] = 'ERROR';
       $response['message'] = $validator->messages();
      }
  } else {
   $response['status'] = 'ERROR';
      $response['message'] = 'User not found';
  }

  return Response::json($response);
 }
}

Kemudian, kita test dengan menggunakan postman dengan memasukan url dan method seperti pada gambar dibawah ini,


Terakhir masukan parameter yang akan kita edit datanya seperti pada gambar dibawah,
Dapat dilihat pada gambar diatas, body yang kita lempar menggunakan postman menggunakan format x-www-form-urlencoded bukan form-data seperti pada API store data, hal ini dikarenakan kita menggunakan method PATCH yang tidak support menggunakan format form-data.

Sehingga hasilnya akan tampak seperti pada gambar dibawah ini,



===DONE!===

Laravel - RESTful project (API show data)


Tutorial sebelumnya kita sudah membuat RESTful untuk store data, pada tutorial kali ini kita akan membuat RESTful sistem untuk menampilkan data berdasarkan ID yang ingin ditampilkan.

Oke, langsung saja kita mulai experimentnya,
Pertama, buat dulu route yang akan mengarah pada API show data dengan mengedit file api.php pada path protected/app/routes/ menjadi seperti ini,
<?php 

//////////
// CRUD //
//////////
//pahamilah group route dibawah
Route::group(array('prefix' => 'crud'), function(){
 Route::get('users', 'Controller\Api\UserController@getUsers');
 Route::post('store-user', 'Controller\Api\UserController@storeUser');
 Route::get('{id}', 'Controller\Api\UserController@showUser');
});

Selanjutnya, buat method baru yang akan mengarahkan pada url show data tersebut dengan mengedit file UserController.php pada path protected/app/controllers/api/ menjadi seperti ini,
<?php namespace Controller\Api;

use Model\User;
use \Response;
use \Validator;
use \Input;
use Illuminate\Http\Request;


class UserController extends \BaseController 
{
 public function getUsers()
 {
  $users = User::get();

  $response['status'] = 'OK';
  $response['result'] = $users;

  return Response::json($response);
 }

 public function storeUser()
 {
  $validator = Validator::make(
   Input::all(),
   array(
    "name"     => "required",
    "username"    => "required|unique:users,username",
    "email"     => "required|email|unique:users,email",
       "password"              => "required|min:6",
   )
  );
  // dd($_POST);
  if ($validator->passes()) {
      $user = User::storeOrUpdateUser(Input::all(), null);
      // dd($_POST);
      $response['status'] = 'OK';
      $response['result'] = $user;
     }
     else {
      $response['status'] = 'ERROR';
      $response['message'] = $validator->messages();
     }

  return Response::json($response);
 }

 public function showUser($id)
 {
  $user = User::find($id);

  if ($user) {
   $response['status'] = 'OK';
   $response['result'] = $user;
  } else {
   $response['status'] = 'ERROR';
   $response['message'] = 'User not found';
  }

  return Response::json($response);
 }
}

Kemudian testing dengan Postman masukan url seperti pada gambar dibawah dan dengan method GET, jangan lupa untuk mengganti "http://localhost:2305/BLOG/" sesuaikan dengan url lokal komputer anda,


Sehingga saat di Send hasilnya akan tampak seperti ini,



===DONE!===

Phalcon - CRUD (Delete)


Akhirnya sampai juga pada tutorial terakhir sistem CRUD Phalcon, pada tutorial terakhir ini kita akan membuat feature delete yang akan digunakan untuk menghapus data user pada database

Oke langsung saja kita mulai tutorialnya,
Pertama, buat terlebih dahulu routenya dengan mengedit file router.php pada path app/config/ menjadi seperti ini,
<?php

$router = $di->getRouter();

// Define your routes here
/**
 * Get user lists data by query
 */
$router->addGet(
    "/user",
    [
        "controller"        => "user",
        "action"            => "index"
    ]
);
$router->addGet(
    "/user/{userId}",
    [
        "controller"        => "user",
        "action"            => "show"
    ]
);
$router->addGet(
    "/user/create",
    [
        "controller"        => "user",
        "action"            => "create"
    ]
);
$router->addPost(
    "/user/create",
    [
        "controller"        => "user",
        "action"            => "save"
    ]
);
$router->addDelete(
    "/user/delete/{userId}",
    [
        "controller"        => "user",
        "action"            => "delete"
    ]
);
$router->addPut(
    "/user/edit/{userId}",
    [
        "controller"        => "user",
        "action"            => "edit"
    ]
);

$router->addGet(
    "/test",
    [
        "controller"        => "test",
        "action"            => "test"
    ]
);

$router->handle();

Selanjutnya, buat method delete dengan mengedit file UserController.php pada path app/controllers/ menjadi seperti ini,
<?php

class UserController extends ControllerBase
{
    public function indexAction()
    {
     $users = Users::find();
     $this->view->title = "Phalcon - Users";
     $this->view->users = $users;
     // dd($users);
    }

    public function showAction($userId)
    {
     $conditions = ['userId'=>$userId];
     $user = Users::findFirst([
      'conditions' => 'id=:userId:',
      'bind' => $conditions,
  ]);
     $this->view->title = "Phalcon - User";
     $this->view->user = $user;
     // dd($users);
    }

    public function createAction()
    {
        $this->view->title = "Phalcon - Create user";
    }

    public function saveAction()
    {
        $name = $this->request->get('name');
        $email = $this->request->get('email');
        $address = $this->request->get('address');

        $user = new Users();
        $user->name = $name;
        $user->email = $email;
        $user->address = $address;

        if ($this->request->isPost()) {
            if ($user->create()) {
                return $this->response->redirect('user');
            }
        } else {
            $this->flash->error('User form is not valid.');
        }
    }

    public function deleteAction($userId)
    {
        $conditions = ['userId'=>$userId];
        $user = Users::findFirst([
            'conditions' => 'id=:userId:',
            'bind' => $conditions,
        ]);
        if ($user->delete() === false) {
            $messages = $user->getMessages();
            foreach ($messages as $message) {
                $this->flash->error($message);
            }
        } else {
            return $this->response->redirect('user');
        }
    }

    public function editAction($userId)
    {
        $conditions = ['userId'=>$userId];
        $user = Users::findFirst([
            'conditions' => 'id=:userId:',
            'bind' => $conditions,
        ]);
        $this->view->title = "Phalcon - User";
        $this->view->user = $user;

        if ($this->request->isPost()) {
            $name = $this->request->get('name');
            $email = $this->request->get('email');
            $address = $this->request->get('address');

            $user->name = $name;
            $user->email = $email;
            $user->address = $address;

            if ($user->save()) {
                return $this->response->redirect('user');
            } else {
                $messages = $user->getMessages();
                foreach ($messages as $message) {
                    $this->flash->error($message);
                }
            }
        }
    }
}

Terakhir buat button atau link untuk menghapus data pada view index dengan mengedit file index.volt pada path app/views/user/ menjadi seperti ini,
{% extends 'layouts/default1.volt' %}

{% block content %}
 <br/>
 Hello codedoct!!!
 <br><br>
 <div class="row">
  <div class="col-md-12">
   user list:
   <br><br>
   <table width="100%">
    <tr>
     <th>Name</th>
     <th>Action</th>
    </tr>
    {% for user in users %}
     <tr>
      <td>{{ user.name }}</td>
      <td><a href="user/{{ user.id }}">show</a> || <a href="user/edit/{{ user.id }}">edit</a> || <a href="user/delete/{{ user.id }}">delete</a></td>
     </tr>
    {% endfor %}
   </table>
   <br>
   <button onclick="window.location.href='user/create'">Create</button>
  </div>
 </div>
{% endblock %}

Sehingga tampilan halaman utamanya akan tampak seperti ini,


===DONE!===

Phalcon - CRUD (Update)


Pada tutorial kemarin kita sudah membuat feature untuk menambahkan data user pada database, tutorial kali kita akan membuat feature untuk mengedit data user pada database

Oke kita mulai saja experimentnya,
Pertama, buat terlebih dahulu routenya dengan cara mengedit file router.php pada path app/config/ edit menjadi seperti ini,
<?php

$router = $di->getRouter();

// Define your routes here
/**
 * Get user lists data by query
 */
$router->addGet(
    "/user",
    [
        "controller"        => "user",
        "action"            => "index"
    ]
);
$router->addGet(
    "/user/{userId}",
    [
        "controller"        => "user",
        "action"            => "show"
    ]
);
$router->addGet(
    "/user/create",
    [
        "controller"        => "user",
        "action"            => "create"
    ]
);
$router->addPost(
    "/user/create",
    [
        "controller"        => "user",
        "action"            => "save"
    ]
);
$router->addPut(
    "/user/edit/{userId}",
    [
        "controller"        => "user",
        "action"            => "edit"
    ]
);

$router->addGet(
    "/test",
    [
        "controller"        => "test",
        "action"            => "test"
    ]
);

$router->handle();

Selanjutnya, tambahkan method baru pada controller dengan cara mengedit file UserController.php pada path app/controllers/ edit menjadi seperti ini,
<?php

class UserController extends ControllerBase
{
    public function indexAction()
    {
     $users = Users::find();
     $this->view->title = "Phalcon - Users";
     $this->view->users = $users;
     // dd($users);
    }

    public function showAction($userId)
    {
     $conditions = ['userId'=>$userId];
     $user = Users::findFirst([
      'conditions' => 'id=:userId:',
      'bind' => $conditions,
  ]);
     $this->view->title = "Phalcon - User";
     $this->view->user = $user;
     // dd($users);
    }

    public function createAction()
    {
        $this->view->title = "Phalcon - Create user";
    }

    public function saveAction()
    {
        $name = $this->request->get('name');
        $email = $this->request->get('email');
        $address = $this->request->get('address');

        $user = new Users();
        $user->name = $name;
        $user->email = $email;
        $user->address = $address;

        if ($this->request->isPost()) {
            if ($user->create()) {
                return $this->response->redirect('user');
            }
        } else {
            $this->flash->error('User form is not valid.');
        }
    }

    public function editAction($userId)
    {
        $conditions = ['userId'=>$userId];
        $user = Users::findFirst([
            'conditions' => 'id=:userId:',
            'bind' => $conditions,
        ]);
        $this->view->title = "Phalcon - User";
        $this->view->user = $user;

        if ($this->request->isPost()) {
            $name = $this->request->get('name');
            $email = $this->request->get('email');
            $address = $this->request->get('address');

            $user->name = $name;
            $user->email = $email;
            $user->address = $address;

            if ($user->save()) {
                return $this->response->redirect('user');
            } else {
                $messages = $user->getMessages();
                foreach ($messages as $message) {
                    $this->flash->error($message);
                }
            }
        }
    }
}

Kemudian, buat file view baru dengan nama edit.volt pada path app/views/user/ dan isikan code berikut,
{% extends 'layouts/default1.volt' %}

{% block content %}
 <br/>
 Hello codedoct!!!
 <br><br>
 <div class="row">
  <div class="col-md-12">
   <form method="POST">
    <div class="form-group">
     <label>Nama user</label>
     <input type="text" name="name" class="form-control" placeholder="Type your name" required value="{{ user.name }}">
    </div>
    <div class="form-group">
     <label>Email user</label>
     <input type="email" name="email" class="form-control" placeholder="Type your email" required value="{{ user.email }}">
    </div>
    <div class="form-group">
     <label>Address user</label>
     <textarea name="address" class="form-control" placeholder="Type your address" required>{{ user.address }}</textarea>
    </div>
    <input type="submit" value="Save"> <button type="button" onclick="window.location.href='../../user'">Cancel</button>
   </form>
  </div>
 </div>
{% endblock %}

Terakhir, tambahkan link untuk kehalaman update dengan cara edit file index.volt pada path app/views/user/ menjadi seperti ini,
{% extends 'layouts/default1.volt' %}

{% block content %}
 <br/>
 Hello codedoct!!!
 <br><br>
 <div class="row">
  <div class="col-md-12">
   user list:
   <br><br>
   <table width="100%">
    <tr>
     <th>Name</th>
     <th>Action</th>
    </tr>
    {% for user in users %}
     <tr>
      <td>{{ user.name }}</td>
      <td><a href="user/{{ user.id }}">show</a> || <a href="user/edit/{{ user.id }}">edit</a></td>
     </tr>
    {% endfor %}
   </table>
   <br>
   <button onclick="window.location.href='user/create'">Create</button>
  </div>
 </div>
{% endblock %}

Sehingga tampilan halaman editnya akan tampak seperti ini,



===DONE!===

Phalcon - CRUD (Create)


Pada tutorial sebelumnya kita sudah membuat sistem read data user dari database dan menampilkannya dalam list maupun detail per masing-masing user. Pada tutorial kali ini kita akan membuat sistem create untuk menginputkan atau menambah data user pada database

Oke kita langsung saja memulai eksperiment create data pada phalcon,
Pertama, buat terlebih dahulu route untuk create dengan mengedit file router.php pada path app/config/ menjadi seperti ini,
<?php

$router = $di->getRouter();

// Define your routes here
/**
 * Get user lists data by query
 */
$router->addGet(
    "/user",
    [
        "controller"        => "user",
        "action"            => "index"
    ]
);
$router->addGet(
    "/user/{userId}",
    [
        "controller"        => "user",
        "action"            => "show"
    ]
);
$router->addGet(
    "/user/create",
    [
        "controller"        => "user",
        "action"            => "create"
    ]
);
$router->addPost(
    "/user/create",
    [
        "controller"        => "user",
        "action"            => "save"
    ]
);

$router->addGet(
    "/test",
    [
        "controller"        => "test",
        "action"            => "test"
    ]
);

$router->handle();

Selanjutnya, buat controller untuk menampilkan halaman create dan untuk menyimpan data user baru dengan mengedit file UserController.php pada path app/controllers/ menjadi seperti ini,
<?php

class UserController extends ControllerBase
{
    public function indexAction()
    {
     $users = Users::find();
     $this->view->title = "Phalcon - Users";
     $this->view->users = $users;
     // dd($users);
    }

    public function showAction($userId)
    {
     $conditions = ['userId'=>$userId];
     $user = Users::findFirst([
      'conditions' => 'id=:userId:',
      'bind' => $conditions,
  ]);
     $this->view->title = "Phalcon - User";
     $this->view->user = $user;
     // dd($users);
    }

    public function createAction()
    {
        $this->view->title = "Phalcon - Create user";
    }

    public function saveAction()
    {
        $name = $this->request->get('name');
        $email = $this->request->get('email');
        $address = $this->request->get('address');

        $user = new Users();
        $user->name = $name;
        $user->email = $email;
        $user->address = $address;

        if ($this->request->isPost()) {
            if ($user->create()) {
                return $this->response->redirect('user');
            }
        } else {
            $this->flash->error('User form is not valid.');
        }
    }
}

Kemudian, buat file view untuk create dengan membuat file baru dengan nama create.volt pada path app/views/user/ dan isikan code berikut,
{% extends 'layouts/default1.volt' %}

{% block content %}
 <br/>
 Hello codedoct!!!
 <br><br>
 <div class="row">
  <div class="col-md-12">
   <form method="POST">
    <div class="form-group">
     <label>Nama user</label>
     <input type="text" name="name" class="form-control" placeholder="Type your name" required>
    </div>
    <div class="form-group">
     <label>Email user</label>
     <input type="email" name="email" class="form-control" placeholder="Type your email" required>
    </div>
    <div class="form-group">
     <label>Address user</label>
     <textarea name="address" class="form-control" placeholder="Type your address" required></textarea>
    </div>
    <input type="submit" value="Save"> <button type="button" onclick="window.location.href='../user'">Cancel</button>
   </form>
  </div>
 </div>
{% endblock %}

Terakhir, edit file view index.volt pada path app/views/user/ menjadi seperti ini,
{% extends 'layouts/default1.volt' %}

{% block content %}
 <br/>
 Hello codedoct!!!
 <br><br>
 <div class="row">
  <div class="col-md-12">
   user list:
   <br><br>
   <table width="100%">
    <tr>
     <th>Name</th>
     <th>Action</th>
    </tr>
    {% for user in users %}
     <tr>
      <td>{{ user.name }}</td>
      <td><a href="user/{{ user.id }}">show</a></td>
     </tr>
    {% endfor %}
   </table>
   <br>
   <button onclick="window.location.href='user/create'">Create</button>
  </div>
 </div>
{% endblock %}

Sehingga hasilnya akan tampak seperti ini,



===DONE!===

Phalcon - CRUD (Read)



Back to phalcon, pada tutorial kemarin kita sudah sampai pada experiment menambahkan mirgation dan seeder secara manual pada project phalcon kita,

Pada tutorial kali ini, kita akan mulai bereksperiment membuat sistem crud, untuk tutorial crud yang pertama yaitu read, yang berarti mendapatkan data dari database yang kemudian menampilkannya pada project kita.

Oke langsung saja kita mulai experimentnya,
Pertama, edit file router.php pada path app/config/ yang satu mengarah pada list user dan yang satu lagi digunakan untuk melihat detail user,

<?php

$router = $di->getRouter();

// Define your routes here
/**
 * Get user lists data by query
 */
$router->addGet(
    "/user",
    [
        "controller"        => "user",
        "action"            => "index"
    ]
);
$router->addGet(
    "/user/{userId}",
    [
        "controller"        => "user",
        "action"            => "show"
    ]
);

$router->addGet(
    "/test",
    [
        "controller"        => "test",
        "action"            => "test"
    ]
);

$router->handle();

Selajutnya, edit file  UserController.php pada path app/controllers/ menjadi seperti ini
<?php

class UserController extends ControllerBase
{
    public function indexAction()
    {
     $users = Users::find();
     $this->view->title = "Phalcon - Users";
     $this->view->users = $users;
     // dd($users);
    }

    public function showAction($userId)
    {
     $conditions = ['userId'=>$userId];
     $user = Users::findFirst([
      'conditions' => 'id=:userId:',
      'bind' => $conditions,
  ]);
     $this->view->title = "Phalcon - User";
     $this->view->user = $user;
     // dd($users);
    }
}

Kemudian, buat file view index.volt pada path app/views/user/ yang digunakan untuk menampilkan list user kemudian isikan code berikut,
{% extends 'layouts/default1.volt' %}

{% block content %}
 <br/>
 Hello codedoct!!!
 <br><br>
 <div class="row">
  <div class="col-md-12">
   user list:
   <br><br>
   <table width="100%">
    <tr>
     <th>Name</th>
     <th>Action</th>
    </tr>
    {% for user in users %}
     <tr>
      <td>{{ user.name }}</td>
      <td><a href="user/{{ user.id }}">show</a></td>
     </tr>
    {% endfor %}
   </table>
   
  </div>
 </div>
{% endblock %}

Terakhir, buat file view show.volt pada path app/views/user yang digunakan untuk menampilkan detail user kemudian isikan code berikut,
{% extends 'layouts/default1.volt' %}

{% block content %}
 <br/>
 User Detail
 <br><br>
 <table width="100%">
  <tr>
   <td>Name</td><td>:</td><td>{{ user.name }}</td>
  </tr>
  <tr>
   <td>Email</td><td>:</td><td>{{ user.email }}</td>
  </tr>
  <tr>
   <td>Address</td><td>:</td><td>{{ user.address }}</td>
  </tr>
 </table>
 <br><br>
 <button onclick="window.location.href='../user'">Back</button>
{% endblock %}

Sehingga tampilannya akan tampak seperti ini,



===DONE!===

Phalcon - Migration and seed


Pada tutorial kemarin kita sudah berkenalan dengan syntax-syntax phalcon,

Tutorial kali ini kita akan membuat migration dan seeder database, dikarenakan sampai saat tutorial ini dibuat phalcon belum menyediakan function untuk migration dan seed database maka kita akan membuatnya dengan cara manual.

Oke langsung saja kita mulai tutorialnya pertama, buat file mirgate.php pada path app/migrations/ dan isikan code berikut,
<?php

defined('BASE_PATH') || define('BASE_PATH', getenv('BASE_PATH') ?: realpath(dirname(__FILE__) . '/../..'));
defined('APP_PATH') || define('APP_PATH', BASE_PATH . '/app');

if (!function_exists('env')) {
    // Use composer autoloader to load vendor classes
 require_once BASE_PATH . '/vendor/autoload.php';

 /**
  * Environment variables
  */
 $dotenv = new Dotenv\Dotenv(BASE_PATH . '/');
 $dotenv->load();
}

$host = getenv('DB_HOST');
$user = getenv('DB_USER');
$pass = getenv('DB_PASS');
$dbname = getenv('DB_NAME');

try {
    $db = new PDO("mysql:host=$host;CHARSET=utf8;COLLATE=utf8_unicode_ci", $user, $pass);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->exec("CREATE DATABASE IF NOT EXISTS `$dbname`; CREATE USER '$user'@'localhost' IDENTIFIED BY '$pass'; GRANT ALL ON `$dbname`.* TO '$user'@'localhost'; FLUSH PRIVILEGES; DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci") 
    or die(print_r($db->errorInfo(), true));
} catch(PDOException $e) {
    die("DB ERROR: ". $e->getMessage());
}

//migrate
include_once "users.php";

//seed
include_once "user_seed.php";

echo "\n Success All!!! \n";

Selanjutnya, pada path yang sama buat file users.php dan isikan code berikut,
<?php

$tablename = "users";

try {
    $db = new PDO("mysql:dbname=$dbname;host=$host;CHARSET=utf8;COLLATE=utf8_unicode_ci", $user, $pass);
    $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    $db->exec("CREATE TABLE IF NOT EXISTS $tablename(
      id bigint( 20 ) AUTO_INCREMENT PRIMARY KEY,
      name varchar( 50 ) COLLATE utf8_unicode_ci NOT NULL,
      email varchar( 150 ) COLLATE utf8_unicode_ci NOT NULL, 
      address text( 150 ) COLLATE utf8_unicode_ci,
      created_at timestamp DEFAULT CURRENT_TIMESTAMP,
      updated_at timestamp DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci");
    print("Created $tablename Table success.\n");
} catch(PDOException $e) {
    echo $e->getMessage();
}

Terakhir, pada path yang sama juga buat file user_seed.php dan isikan code berikut,
<?php

$tablename = "users";

try {
    $db = new PDO("mysql:dbname=$dbname;host=$host;CHARSET=utf8;COLLATE=utf8_unicode_ci", $user, $pass);
    $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    $db->exec("TRUNCATE TABLE $tablename;");
    $db->exec("INSERT INTO $tablename (name, email, address) VALUES ('Dracule', 'dracule@mail.com', 'Jalan ganteng kali no. 1')");
    $db->exec("INSERT INTO $tablename (name, email, address) VALUES ('Mihawk', 'mihawk@mail.com', 'Jalan ganteng kali no. 2')");
    print("Seed $tablename Table success.\n");
} catch(PDOException $e) {
    echo $e->getMessage();
}

Sehingga tampilan struktur file nya akan tampak seperti ini,


Untuk mengetestnya, buka terminal dan arahkan pada path project anda, kemudian masukan syntax berikut pada terminal,
php app/mirgations/mirgate.php

Sehingga tampilanya akan tampak seperti ini,


Dan hasilnya akan tampak seperti ini,


===DONE!===