menu

Engine PHP - Upload and download file


Hello codedoctors,

Kali ini codedoct akan sharing ilmu untuk membuat sebuah engine yang dapat meng-upload dan men-download suatu file. engine ini akan kita buat menggunakan bahasa PHP native.

Oke langsung saja kita mulai tutorialnya,

Pertama, buat folder projectnya terlebih dahulu dalam hal ini codedoct akan memberi nama file test-upload-download-file dan buat folder baru juga didalammnya dengan nama file sehingga struktur foldernya akan tampak seperti ini,


Kemudian, buat tabel pada database dengan struktur seperti ini,


Setelah itu, buat file baru dengan nama index.php seperti struktur diatas, dan isikan code berikut,
<?php
 include_once('uploadController.php');
?>
<head>
 <title>Hello | Budy</title>
</head>
<body>
 <div class="show-file">
  <ul>
   <?php
     $sql="SELECT * FROM upload_and_download_file";
     $hsl=mysql_query($sql,$db);
     $no=0;
     while(list($id,$name,$created_at)=mysql_fetch_array($hsl)){
       $no++;?>
      <li><?=$no?></li>
        <ul>
       <li><?=$name?></li>
       <li><?=$created_at?></li>
       <li><a href="downloadController.php?file_name=<?=$name?>">Download</a></li>
      </ul>
    <?php }
   ?>
  </ul>
 </div>
 <div class="upload-file">
  <form action="uploadController.php" method="post" enctype="multipart/form-data">
   <input type="file" name="uploadFile">
   <input type="submit" value="Upload" name="upload">
  </form>
 </div>
</body>

Selanjutnya, buat file baru dengan nama connection.php dan isikan code berikut,
<?php
 $servername = "localhost";
 $username = "root";
 $password = "root";
 $dbname = "test";

 $db=mysql_connect($servername,$username,$password);
 mysql_select_db($dbname,$db);
?>

Kemudian, buat file baru dengan nama model.php dan isikan code berikut,
<?php
 class FileController 
 {
  public function saveFile($name)
  {
   include 'connection.php';
   $sql="INSERT INTO upload_and_download_file (name,created_at) VALUES ";
      $sql.="('$name',NOW())";
    $save = mysql_query($sql,$db);

   if ($save) {
       return true;
   } else {
       echo "Error";
   } 
  }
 }
?>

Terakhir buat file baru dengan nama uploadController.php dan downloadController.php dan isikan code berikut,
uploadController.php
<?php
 include_once('connection.php');
 include_once('model.php');

 if (isset($_POST['upload'])) {
  $errors  = array();
  $file_name  = $_FILES['uploadFile']['name'];
  $file_size  = $_FILES['uploadFile']['size'];
  $file_tmp  = $_FILES['uploadFile']['tmp_name'];
  $file_ext = strtolower(end(explode('.',$_FILES['uploadFile']['name'])));

  $extensions = array("txt");

  if(in_array($file_ext,$extensions)===false){
   $errors[]="extension not allowed, please choose a TXT file.";
  }

  if($file_size > 1024000){
   $errors[]='File size must be excately 1 MB';
  }

  if(empty($errors)==true){
   //save file to folder file
   $filename = strtotime('now').'_'.$file_name;
   move_uploaded_file($file_tmp,"file/".$filename);

   //save file to database
   $model = new FileController;
   $save_file = $model->saveFile($filename);
   if ($save_file) {
    //back to project
    $path_project = "http://localhost/test/test-upload-download-file/";
    header("Location: $path_project");
   }
  }else{
   print_r($errors);
   ?><br><a href="/test/test-upload-download-file">Back</a><?php
  }
 }
?>

downloadController.php
<?php
    $file_name = $_GET['file_name'];
    $file = "file/".$file_name;

    if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist.");

    header("Pragma: public", true);
    header("Expires: 0"); // set expiration time
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header("Content-Disposition: attachment; filename=".basename($file));
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".filesize($file));
    die(file_get_contents($file));
?>

Sehingga hasilnya akan tampak seperti gambar dibawah ini


Untuk enginenya bisa didownload disini,

===DONE!===

Laravel - Relation pada model (belongsToMany)


Hello codedoctors,

Setelah pada tutorial sebelumnya kita sudah membuat relasi tabel hasOne, tutorial kali ini kita akan membuat sebuah relasi tabel pada model dengan fungsi relasi belongsToMany yang berarti banyak field pada suatu tabel mempunyai banyak field pada tabel lain.

Dalam tutorial kali ini kita akan merelasikan antara tabel users dan tabel users itu sendiri dengan menggunakan pivot yang akan kita beri nama followes.

Oke untuk lebih memahaminya kita mulai saja tutorialnya,

Pertama, buat terlebih dahulu tabel pivotnya dengan nama followes, dengan cara php artisan migrate:make create_followes_table pada terminal atau cmd, sehingga akan otomatis membuat file migrate baru dengan nama <tanggal>_create_followes_table.php pada path protected/app/database/migrations/. Kemudian isi dengan code berikut,
<?php

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

class CreateFollowesTable extends Migration {

 /**
  * Run the migrations.
  *
  * @return void
  */
 public function up()
 {
  Schema::create('followes', function($table){
   $table->integer('following_user_id')->index('followes_following_user_id');
   $table->integer('follower_user_id')->index('followes_follower_user_id');
   $table->timestamps();
   $table->softDeletes();
   $table->primary(['following_user_id','follower_user_id']);
  });

  Schema::table('followes', function(Blueprint $table)
  {
   $table->foreign('following_user_id', 'followes_ibfk_1')->references('id')->on('users')->onUpdate('CASCADE')->onDelete('CASCADE');
   $table->foreign('follower_user_id', 'followes_ibfk_2')->references('id')->on('users')->onUpdate('CASCADE')->onDelete('CASCADE');
  });
 }

 /**
  * Reverse the migrations.
  *
  * @return void
  */
 public function down()
 {
  Schema::table('followes', function(Blueprint $table)
  {
   $table->dropForeign('followes_ibfk_1');
   $table->dropForeign('followes_ibfk_2');
  });

  Schema::drop('followes');
 }

}

Selanjutnya, buat file seeder baru dengan nama FollowSeeder.php pada path protected/app/database/seeds/ isi dengan code berikut,
<?php
 
class FollowSeeder extends Seeder
{
    public function run()
    {
        DB::table('followes')->delete();
        DB::table('followes')->insert(array (
            array (
                'following_user_id'       => 1,
                'follower_user_id'     => 2,
            ),
            array (
                'following_user_id'       => 2,
                'follower_user_id'     => 1,
            ),
            array (
                'following_user_id'       => 1,
                'follower_user_id'     => 3,
            ),
            array (
                'following_user_id'       => 2,
                'follower_user_id'     => 3,
            ),
        ));
    }
}

Kemudian, edit file seeder UserSeeder.php dan DatabaseSeeder.php pada path protected/app/database/seeds/ edit menjadi seperti ini,
UserSeeder.php
<?php
 
class UserSeeder extends Seeder
{
    public function run()
    {
        DB::table('users')->delete();
        DB::table('users')->insert(array (
            array (
                'id'       => 1,
                'name'     => 'Dracule Mihawk',
                'username' => 'mihawk',
                'email'    => 'mihawk@gmail.com',
                'role_id'     => 1,
                'password' => Hash::make('rahasiakampret'),
            ),
            array (
                'id'       => 2,
                'name'     => 'Trafalgar Law',
                'username' => 'trafa',
                'email'    => 'trafa@gmail.com',
                'role_id'     => 2,
                'password' => Hash::make('rahasiakampret'),
            ),
            array (
                'id'       => 3,
                'name'     => 'Dark King',
                'username' => 'dk',
                'email'    => 'dk@gmail.com',
                'role_id'     => 2,
                'password' => Hash::make('rahasiakampret'),
            ),
        ));
    }
}
Pada UserSeeder diatas kita menambahkan seeder user baru yaitu Dark King.

DatabaseSeeder.php
<?php

class DatabaseSeeder extends Seeder {

 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
  // Eloquent::unguard();
  DB::statement('SET FOREIGN_KEY_CHECKS=0;');

  $this->call('UserSeeder');
  $this->call('AddressSeeder');
  $this->call('RoleSeeder');
  $this->call('CompanySeeder');
  $this->call('FollowSeeder');

  DB::statement('SET FOREIGN_KEY_CHECKS=1;');
  \Cache::flush();
 }

}

Setelah itu, buat file model baru dengan nama Follow.php pada path protected/app/models/ dan isi dengan code berikut,
<?php namespace Model;

class Follow extends \Eloquent {

 /**
  * The database table used by the model.
  *
  * @var string
  */
 protected $table = 'followes';

 /**
  * The attributes excluded from the model's JSON form.
  *
  * @var array
  */
 protected $hidden = array('');
}

Edit file model User.php pada path protected/app/models/ menjadi seperti ini,
<?php namespace Model;

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
use Illuminate\Database\Eloquent\Model;
use \Eloquent;

class User extends Eloquent implements UserInterface, RemindableInterface {

 use UserTrait, RemindableTrait;

 /**
  * The database table used by the model.
  *
  * @var string
  */
 protected $table = 'users';

 /**
  * The attributes excluded from the model's JSON form.
  *
  * @var array
  */
 protected $hidden = array('password', 'remember_token');

 // Relation
 public function addresses()
    {
        return $this->hasMany('Model\Address');
    }

    public function role()
    {
        return $this->belongsTo('Model\Role');
    }

    public function company()
    {
        return $this->hasOne('Model\Company');
    }

    // follower dan following berbeda, coba pahami lebih detail
    public function follower()
    {
        return $this->belongsToMany('Model\User', 'followes', 'following_user_id', 'follower_user_id');
    }

    public function following()
    {
        return $this->belongsToMany('Model\User', 'followes', 'follower_user_id', 'following_user_id');
    }
}
Pada code diatas pahamilah code berikut: belongsToMany('nama_model_yang_akan berelasi', 'nama_tabel_pivot', 'foreign_key', 'relasi_foreign_key').

Edit pula file controller UserController.php pada path protected/app/controllers/relation/ menjadi seperti ini,
<?php namespace Controller\Relation;

use Model\User;
use \View;

class UserController extends \BaseController 
{
 public function getUserDetail($user_id)
 {
  $user = User::where('id', $user_id)->first();
  //code dibawah untuk panggil relasi dari model user
  if($user){
   $address = $user->addresses;
   $role = $user->role;
   $company = $user->company;
   $follower = $user->follower;
   $following = $user->following;
  }

  return View::make('web.relation.show-user-detail')->with('user', $user);
 }
}

Terakhir edit file blade show-user-detail.blade.php pada path protected/app/views/web/relation/ menjadi seperti ini,
@extends('layouts/web/master')
@section('content')
 <?php $title = "User" ?>
 <div class="isi">
  <div class="row">
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
           <th>ID</th>
           <th>NAME</th>
           <th>USERNAME</th>
           <th>EMAIL</th>
        </tr>
      </thead>
      <tbody>
        <tr>
      <td>{{ $user->id }}</td>
      <td>{{ $user->name }}</td>
      <td>{{ $user->username }}</td>
      <td>{{ $user->email }}</td>
        </tr>
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>Nama alamat</th>
      <th>Kota</th>
      <th>Provinsi</th>
      <th>Alamat</th>
      <th>Zipcode</th>
      <th>Phone</th>
        </tr>
      </thead>
      <tbody>
       @forelse($user['addresses'] as $address)
         <tr>
       <td>{{ $address->name_address }}</td>
       <td>{{ $address->city }}</td>
       <td>{{ $address->province }}</td>
       <td>{{ $address->address }}</td>
       <td>{{ $address->zipcode }}</td>
       <td>{{ $address->phone }}</td>
         </tr>
        @empty
         Address not found
        @endforelse
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>Role ID</th>
      <th>Role Name</th>
        </tr>
      </thead>
      <tbody>
       @if($user['role'])
         <tr>
       <td>{{ $user['role']->id }}</td>
       <td>{{ $user['role']->name }}</td>
         </tr>
        @else
         Role not found
        @endif
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>Company Name</th>
      <th>Position</th>
        </tr>
      </thead>
      <tbody>
       @if($user['company'])
         <tr>
       <td>{{ $user['company']->name }}</td>
       <td>{{ $user['company']->position }}</td>
         </tr>
        @else
         Role not found
        @endif
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>No</th>
      <th>Follower</th>
        </tr>
      </thead>
      <tbody>
       <?php $no=1 ?>
       @forelse($user['follower'] as $follower)
         <tr>
       <td>{{ $no++ }}</td>
       <td>{{ $follower->name }}</td>
         </tr>
        @empty
         Follower not found
        @endif
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>No</th>
      <th>Following</th>
        </tr>
      </thead>
      <tbody>
       <?php $no=1 ?>
       @forelse($user['following'] as $following)
         <tr>
       <td>{{ $no++ }}</td>
       <td>{{ $following->name }}</td>
         </tr>
        @empty
         Follower not found
        @endif
       </tbody>
   </table>
  </div>
 </div>
@stop

Jangan lupa untuk mengcompile composer setelah membuat file model baru dengan cara


Sehingga hasilnya akan tampak seperti ini,


===DONE!===

Laravel - Relation pada model (hasOne)


Hello codedoctors, kembali lagi codedoct akan share ilmu gratis.

Melanjutkan tutorial sebelumnya, kita sudah membuat sebuah relasi belongsTo pada model. Pada tutorial kali ini kita akan membuat relasi hasOne pada model, dimana pada prinsipnya relasi ini akan membuat sebuah field tabel berelasi dengan sebuah field dari tabel lain.

Tabel yang akan kita relasikan adalah tabel user dengan tabel company, oke langsung saja kita mulai tutorialnya,

Pertama, kita buat dulu tabel company-nya dengan cara php artisan migrate:make create_companies_table pada terminal atau cmd, sehingga akan otomatis membuat file migrate baru dengan nama <tanggal>_create_companies_table.php pada path protected/app/database/migrations/. Kemudian isi dengan code berikut,
<?php

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

class CreateCompaniesTable extends Migration {

 /**
  * Run the migrations.
  *
  * @return void
  */
 public function up()
 {
  Schema::create('companies', function($table){
   $table->integer('id', true);
   $table->integer('user_id')->index('companies_user_id');
   $table->string('name');
   $table->string('position');
   $table->timestamps();
  });

  Schema::table('companies', function(Blueprint $table)
        {
            $table->foreign('user_id', 'companies_ibfk_1')->references('id')->on('users')->onUpdate('CASCADE')->onDelete('CASCADE');
        });
 }

 /**
  * Reverse the migrations.
  *
  * @return void
  */
 public function down()
 {
  Schema::table('companies', function(Blueprint $table)
  {
   $table->dropForeign('companies_ibfk_1');
  });

  Schema::drop('companies');
 }

}

Kemudian, buat file seeder baru dengan nama CompanySeeder.php pada path protected/app/database/seeds/ isi dengan code berikut,
<?php
 
class CompanySeeder extends Seeder
{
    public function run()
    {
        DB::table('companies')->delete();
        DB::table('companies')->insert(array (
            array (
                'id'       => 1,
                'user_id'  => 1,
                'name'     => 'PT. HAHA',
                'position' => 'Software Engineer',
            ),
            array (
                'id'       => 2,
                'user_id'  => 2,
                'name'     => 'PT. HUHU',
                'position' => 'Marketing',
            ),
        ));
    }
}

Edit file DatabaseSeeder.php pada path protected/app/database/seeds/ dengan menambahkan seeder CompanySeeder menjadi seperti ini,
<?php

class DatabaseSeeder extends Seeder {

 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
  // Eloquent::unguard();
  DB::statement('SET FOREIGN_KEY_CHECKS=0;');

  $this->call('UserSeeder');
  $this->call('AddressSeeder');
  $this->call('RoleSeeder');
  $this->call('CompanySeeder');

  DB::statement('SET FOREIGN_KEY_CHECKS=1;');
  \Cache::flush();
 }

}

Setelah itu edit file UserController.php pada path protected/app/controllers/relation/ menjadi seperti ini,
<?php namespace Controller\Relation;

use Model\User;
use \View;

class UserController extends \BaseController 
{
 public function getUserDetail($user_id)
 {
  $user = User::where('id', $user_id)->first();
  //code dibawah untuk panggil relasi dari model user
  if($user){
   $address = $user->addresses;
   $role = $user->role;
   $company = $user->company;
  }
  return View::make('web.relation.show-user-detail')->with('user', $user);
 }
}

Edit file model User.php dan buat file model baru dengan nama Company.php pada path protected/app/models/ sehingga code keduanya akan tampak seperti ini,
User.php

<?php namespace Model;

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
use Illuminate\Database\Eloquent\Model;
use \Eloquent;

class User extends Eloquent implements UserInterface, RemindableInterface {

 use UserTrait, RemindableTrait;

 /**
  * The database table used by the model.
  *
  * @var string
  */
 protected $table = 'users';

 /**
  * The attributes excluded from the model's JSON form.
  *
  * @var array
  */
 protected $hidden = array('password', 'remember_token');

 // Relation
 public function addresses()
    {
        return $this->hasMany('Model\Address');
    }

    public function role()
    {
        return $this->belongsTo('Model\Role');
    }

    public function company()
    {
        return $this->hasOne('Model\Company');
    }
}

Company.php
<?php namespace Model;

class Company extends \Eloquent {

 /**
  * The database table used by the model.
  *
  * @var string
  */
 protected $table = 'companies';

 /**
  * The attributes excluded from the model's JSON form.
  *
  * @var array
  */
 protected $hidden = array('');
}

Terakhir edit file blade dengan nama show-user-detail.blade.php pada path protected/app/views/web/relation/ menjadi seperti ini,
@extends('layouts/web/master')
@section('content')
 <?php $title = "User" ?>
 <div class="isi">
  <div class="row">
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
           <th>ID</th>
           <th>NAME</th>
           <th>USERNAME</th>
           <th>EMAIL</th>
        </tr>
      </thead>
      <tbody>
        <tr>
      <td>{{ $user->id }}</td>
      <td>{{ $user->name }}</td>
      <td>{{ $user->username }}</td>
      <td>{{ $user->email }}</td>
        </tr>
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>Nama alamat</th>
      <th>Kota</th>
      <th>Provinsi</th>
      <th>Alamat</th>
      <th>Zipcode</th>
      <th>Phone</th>
        </tr>
      </thead>
      <tbody>
       @forelse($user['addresses'] as $address)
         <tr>
       <td>{{ $address->name_address }}</td>
       <td>{{ $address->city }}</td>
       <td>{{ $address->province }}</td>
       <td>{{ $address->address }}</td>
       <td>{{ $address->zipcode }}</td>
       <td>{{ $address->phone }}</td>
         </tr>
        @empty
         Address not found
        @endforelse
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>Role ID</th>
      <th>Role Name</th>
        </tr>
      </thead>
      <tbody>
       @if($user['role'])
         <tr>
       <td>{{ $user['role']->id }}</td>
       <td>{{ $user['role']->name }}</td>
         </tr>
        @else
         Role not found
        @endif
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>Company Name</th>
      <th>Position</th>
        </tr>
      </thead>
      <tbody>
       @if($user['company'])
         <tr>
       <td>{{ $user['company']->name }}</td>
       <td>{{ $user['company']->position }}</td>
         </tr>
        @else
         Role not found
        @endif
       </tbody>
   </table>
  </div>
 </div>
@stop

Jangan lupa untuk mengcompile composer setelah membuat file model baru dengan cara


Sehingga tampilannya akan tampak seperti ini,


Coba cek database (phpmyadmin), saat anda menghapus salah satu field dari tabel users maka relasi tabel companies dan addresses juga ikut terhapus sedangkan field pada tabel role tidak terhapus, hal ini disebabkan karena relasi tabel companies menggunakan hasOne dan relasi tabel addresses menggunakan relasi hasMany dimana keduanya membutuhkan tabel users sebagai induknya (untuk lebih jelasnya pahamilah sendiri).

===DONE!===

Laravel - Relation pada model (belongsTo)


Kembali share ilmu,

Tutorial sebelumnya kita sudah membuat relation tabel pada model untuk hasMany, tutorial kali ini kita akan membuat relation tabel pada model untuk belongsTo(banyak field bisa punya satu field relasi).

Oke langsung saja kita mulai prakteknya,

Pertama, buat dulu tabel role nya dengan cara php artisan migrate:make create_roles_table pada terminal atau cmd, sehingga akan otomatis membuat file migrate baru dengan nama <tanggal>_create_roles_table.php pada path protected/app/database/migrations/. Isi dengan code berikut,
<?php

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

class CreateRolesTable extends Migration {

 /**
  * Run the migrations.
  *
  * @return void
  */
 public function up()
 {
  Schema::create('roles', function($table){
   $table->integer('id', true);
   $table->string('name');
   $table->timestamps();
   $table->softDeletes();
  });

  Schema::table('users', function(Blueprint $table)
        {
            $table->foreign('role_id', 'users_ibfk_1')->references('id')->on('roles')->onUpdate('CASCADE')->onDelete('CASCADE');
        });
 }

 /**
  * Reverse the migrations.
  *
  * @return void
  */
 public function down()
 {
  Schema::table('users', function(Blueprint $table)
  {
   $table->dropForeign('users_ibfk_1');
  });
  
  Schema::drop('roles');
 }

}

Selanjutnya, edit file migrate <tanggal>_create_users_table.php pada path protected/app/database/migrations/ menjadi seperti ini,
<?php
//ini database laravel
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration {

 /**
  * Run the migrations.
  *
  * @return void
  */
 public function up()
 {
  Schema::create('users', function($table){
   $table->integer('id', true);
   $table->string('name');
   $table->string('username')->unique('users_username');
   $table->string('email')->unique('users_email');
   $table->string('password');
   $table->string('remember_token', 100)->nullable();
   $table->integer('role_id')->index('users_role_id')->nullable();
   $table->timestamps();
   $table->softDeletes();
  });
 }

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

}

Edit pula file seednya dengan nama UserSeeder.php pada path protected/app/database/seeds/ edit menjadi seperti ini,
<?php
 
class UserSeeder extends Seeder
{
    public function run()
    {
        DB::table('users')->delete();
        DB::table('users')->insert(array (
            array (
                'id'       => 1,
                'name'     => 'Dracule Mihawk',
                'username' => 'mihawk',
                'email'    => 'mihawk@gmail.com',
                'role_id'     => 1,
                'password' => Hash::make('rahasiakampret'),
            ),
            array (
                'id'       => 2,
                'name'     => 'Trafalgar Law',
                'username' => 'trafa',
                'email'    => 'trafa@gmail.com',
                'role_id'     => 2,
                'password' => Hash::make('rahasiakampret'),
            ),
        ));
    }
}

Kemudian, buat file seeder baru dengan nama RoleSeeder.php pada path protected/app/database/seeds/ isi dengan code berikut,
<?php
 
class RoleSeeder extends Seeder
{
    public function run()
    {
        DB::table('roles')->delete();
        DB::table('roles')->insert(array (
            array (
                'id'       => 1,
                'name'     => 'admin',
            ),
            array (
                'id'       => 2,
                'name'     => 'user',
            ),
        ));
    }
}

Edit file DatabaseSeeder.php pada path protected/app/database/seeds/ dengan menambahkan seeder RoleSeeder menjadi seperti ini,
<?php

class DatabaseSeeder extends Seeder {

 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
  // Eloquent::unguard();
  DB::statement('SET FOREIGN_KEY_CHECKS=0;');

  $this->call('UserSeeder');
  $this->call('AddressSeeder');
  $this->call('RoleSeeder');

  DB::statement('SET FOREIGN_KEY_CHECKS=1;');
  \Cache::flush();
 }

}

Setelah itu, edit UserController.php (protected/app/controllers/relation), Role.php (protected/app/models), dan User.php (protected/app/models) menjadi seperti ini,
UserController.php
<?php namespace Controller\Relation;

use Model\User;
use \View;

class UserController extends \BaseController 
{
 public function getUserDetail($user_id)
 {
  $user = User::where('id', $user_id)->first();
  //code dibawah untuk panggil relasi dari model user
  if($user){
   $address = $user->addresses;
   $role = $user->role;
  }
  return View::make('web.relation.show-user-detail')->with('user', $user);
 }
}

Role.php
<?php namespace Model;

class Role extends \Eloquent {

 /**
  * The database table used by the model.
  *
  * @var string
  */
 protected $table = 'roles';

 /**
  * The attributes excluded from the model's JSON form.
  *
  * @var array
  */
 protected $hidden = array('');
}

User.php
<?php namespace Model;

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
use Illuminate\Database\Eloquent\Model;
use \Eloquent;

class User extends Eloquent implements UserInterface, RemindableInterface {

 use UserTrait, RemindableTrait;

 /**
  * The database table used by the model.
  *
  * @var string
  */
 protected $table = 'users';

 /**
  * The attributes excluded from the model's JSON form.
  *
  * @var array
  */
 protected $hidden = array('password', 'remember_token');

 // Relation
 public function addresses()
    {
        return $this->hasMany('Model\Address');
    }

    public function role()
    {
        return $this->belongsTo('Model\Role');
    }
}

Selanjutnya, edit file blade readUser.blade.php (protected/app/views/web) dan show-user-detail.blade.php (protected/app/views/web/relation) menjadi seperti ini,
readUser.blade.php

.
.
.
        @foreach($data_user as $users)
          <tr>
             <td>{{ $users->id }}</td>
             <td>{{ $users->name }}</td>
             <td>{{ $users->username }}</td>
             <td>{{ $users->email }}</td>
             <td>{{ $users->password }}</td>
             <td>{{ $users->created_at }}</td>
             <td>
              <a href="{{ URL::to('relation/detail/'.$users->id) }}">Detail<br>
             </td>
             <td>
              <a href="{{ URL::to('crud/update/'.$users->id) }}">Edit<br>
              <a href="{{ URL::to('crud/delete/'.$users->id) }}">Delete
             </td>
          </tr>
        @endforeach
.
.
.

show-user-detail.blade.php
@extends('layouts/web/master')
@section('content')
 <?php $title = "User" ?>
 <div class="isi">
  <div class="row">
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
           <th>ID</th>
           <th>NAME</th>
           <th>USERNAME</th>
           <th>EMAIL</th>
        </tr>
      </thead>
      <tbody>
        <tr>
      <td>{{ $user->id }}</td>
      <td>{{ $user->name }}</td>
      <td>{{ $user->username }}</td>
      <td>{{ $user->email }}</td>
        </tr>
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>Nama alamat</th>
      <th>Kota</th>
      <th>Provinsi</th>
      <th>Alamat</th>
      <th>Zipcode</th>
      <th>Phone</th>
        </tr>
      </thead>
      <tbody>
       @forelse($user['addresses'] as $address)
         <tr>
       <td>{{ $address->name_address }}</td>
       <td>{{ $address->city }}</td>
       <td>{{ $address->province }}</td>
       <td>{{ $address->address }}</td>
       <td>{{ $address->zipcode }}</td>
       <td>{{ $address->phone }}</td>
         </tr>
        @empty
         Address not found
        @endforelse
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>Role ID</th>
      <th>Role Name</th>
        </tr>
      </thead>
      <tbody>
       @if($user['role'])
         <tr>
       <td>{{ $user['role']->id }}</td>
       <td>{{ $user['role']->name }}</td>
         </tr>
        @else
         Role not found
        @endif
       </tbody>
   </table>
  </div>
 </div>
@stop

Terakhir edit file route web.php pada path protected/app/routes/ menjadi seperti ini,

.
.
.
//////////////
// RELATION //
//////////////
//pahamilah group route dibawah
Route::group(array('prefix' => 'relation'), function(){
 Route::get('detail/{user_id}', 'Controller\Relation\UserController@getUserDetail');
});
.
.
.

Jangan lupa untuk mengcompile composer setelah membuat file model baru dengan cara


Sehingga tampilannya akan tampak seperti ini,



===DONE!===

Laravel - Relation pada model (hasMany)


Tutorial sebelumnya kita sudah membuat sebuah relasi tabel pada database, sekarang kita akan membuat relasi tabel pada model laravel sehingga data dapat kita tampilkan pada blade.

Oke langsung saja kita mulai tutorialnya,

Pertama, buat file model baru dengan nama Address.php pada path protected/app/models/ dan isikan code berikut,
<?php namespace Model;

class Address extends \Eloquent {

 /**
  * The database table used by the model.
  *
  * @var string
  */
 protected $table = 'addresses';

 /**
  * The attributes excluded from the model's JSON form.
  *
  * @var array
  */
 protected $hidden = array('user_id');
}

Selanjutnya, edit file model User.php pada path protected/app/models/ dengan menambahkan function relasi hasMany tabel addresses pada tabel users, sehingga model User.php akan tampak seperti ini,
.
.
.
    // Relation
    public function addresses()
    {
        return $this->hasMany('Model\Address');
    }
.
.
.

Kemudian, buat file controller baru untuk menampilkan user detail yang berisikan array tabel users dan tabel addresses, beri nama file controller UserController.php letakkan pada path protected/app/controllers/relation/ dan isikan code berikut,
<?php namespace Controller\Relation;

use Model\User;
use \View;

class UserController extends \BaseController 
{
 public function getUserDetail($user_id)
 {
  $user = User::where('id', $user_id)->first();
  //code dibawah untuk panggil relasi dari model user
  if($user){
   $address = $user->addresses;
  }
  return View::make('web.relation.show-user-detail')->with('user', $user);
 }
}

Setelah itu, edit file route web.php pada path protected/app/routes/ dengan menambahkan code berikut,
.
.
.
//////////////
// RELATION //
//////////////
//pahamilah group route dibawah
Route::group(array('prefix' => 'relation'), function(){
 Route::get('detail/{user_id}', 'Controller\Relation\UserController@getUserDetail');
});
.
.
.

Selanjutnya, buat file blade baru dengan nama show-user-detail.blade.php letakkan pada path protected/app/views/web/relation/ dan isikan code berikut,
@extends('layouts/web/master')
@section('content')
 <?php $title = "User" ?>
 <div class="isi">
  <div class="row">
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
           <th>ID</th>
           <th>NAME</th>
           <th>USERNAME</th>
           <th>EMAIL</th>
        </tr>
      </thead>
      <tbody>
        <tr>
      <td>{{ $user->id }}</td>
      <td>{{ $user->name }}</td>
      <td>{{ $user->username }}</td>
      <td>{{ $user->email }}</td>
        </tr>
       </tbody>
   </table>
   <br>
   <table class="table table-bordered table-hover">
      <thead>
       <tr>
      <th>Nama alamat</th>
      <th>Kota</th>
      <th>Provinsi</th>
      <th>Alamat</th>
      <th>Zipcode</th>
      <th>Phone</th>
        </tr>
      </thead>
      <tbody>
       @forelse($user['addresses'] as $address)
         <tr>
       <td>{{ $address->name_address }}</td>
       <td>{{ $address->city }}</td>
       <td>{{ $address->province }}</td>
       <td>{{ $address->address }}</td>
       <td>{{ $address->zipcode }}</td>
       <td>{{ $address->phone }}</td>
         </tr>
        @empty
         Address not found
        @endforelse
       </tbody>
   </table>
  </div>
   <br>
   <button class="btn btn-default" type="button">Create</button>
 </div>
@stop

Terakhir, edit file blade readUser.blade.php pada path protected/app/views/web/ menjadi seperti ini,
.
.
.
        @foreach($data_user as $users)
          <tr>
             <td>{{ $users->id }}</td>
             <td>{{ $users->name }}</td>
             <td>{{ $users->username }}</td>
             <td>{{ $users->email }}</td>
             <td>{{ $users->password }}</td>
             <td>{{ $users->created_at }}</td>
             <td>
              <a href="{{ URL::to('relation/detail/'.$users->id) }}">Address list<br>
             </td>
             <td>
              <a href="{{ URL::to('crud/update/'.$users->id) }}">Edit<br>
              <a href="{{ URL::to('crud/delete/'.$users->id) }}">Delete
             </td>
          </tr>
        @endforeach
.
.
.

Jangan lupa untuk mengcompile composer setelah membuat file model baru caranya


Sehingga tampilannya akan tampak seperti ini,


Jika field Address list kita klik maka akan menampilkan halaman ini,



===DONE!===

Laravel - Relasi tabel pada database


Hello, kembali lagi codedoct akan share ilmu tentang laravel,

Kali ini codedoct akan membahas cara membuat sebuah relasi tabel pada database menggunakan migration laravel. caranya dengan menambahkan foreign key pada suatu tabel dan tabel tersebut langsung dapat berelasi dengan tabel lain.

Jangan lupa tutorial ini merupakan lanjutan dari tutorial sebelumnya, sehingga untuk mempraktekan tutorial ini anda harus mempraktekkan tutorial2 sebelumnya agar tidak terjadi error.

Oke dari pada bingung, kita langsung saja mulai prakteknya.

Pertama, buat migrate baru dengan cara seperti pada gambar dibawah,


Selanjutnya, buka file hasil migrate:make pada path protected/app/database/migrations/<tanggal>_create_addresses_table.php dan edit menjadi seperti ini,
<?php

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

class CreateAddressesTable extends Migration {

 /**
  * Run the migrations.
  *
  * @return void
  */
 public function up()
 {
  Schema::create('addresses', function($table){
   $table->integer('id', true);
   $table->integer('user_id')->index('addresses_user_id')->nullable();
   $table->string('name_address');
   $table->string('city');
   $table->string('province');
   $table->string('address');
   $table->integer('zipcode');
   $table->string('phone');
   $table->timestamps();
   $table->softDeletes();
  });

  Schema::table('addresses', function(Blueprint $table)
        {
            $table->foreign('user_id', 'addresses_ibfk_1')->references('id')->on('users')->onUpdate('CASCADE')->onDelete('CASCADE');
        });
 }

 /**
  * Reverse the migrations.
  *
  * @return void
  */
 public function down()
 {
  Schema::table('addresses', function(Blueprint $table)
  {
   $table->dropForeign('addresses_ibfk_1');
  });

  Schema::drop('addresses');
 }

}

Kemudian, edit file <tanggal>_create_users_table.php pada path protected/app/database/migrations/ menjadi seperti ini,
<?php
//ini database laravel
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration {

 /**
  * Run the migrations.
  *
  * @return void
  */
 public function up()
 {
  Schema::create('users', function($table){
   $table->integer('id', true);
   $table->string('name');
   $table->string('username')->unique('users_username');
   $table->string('email')->unique('users_email');
   $table->string('password');
   $table->string('remember_token', 100)->nullable();
   $table->timestamps();
   $table->softDeletes();
  });
 }

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

}

Setelah itu, edit pula file UserSeeder.php pada path protected/app/database/seeds/ menjadi seperti ini,
<?php
 
class UserSeeder extends Seeder
{
    public function run()
    {
        DB::table('users')->delete();
        DB::table('users')->insert(array (
            array (
                'name'     => 'Dracule Mihawk',
                'username' => 'mihawk',
                'email'    => 'mihawk@gmail.com',
                'password' => Hash::make('rahasiakampret'),
            ),
            array (
                'name'     => 'Trafalgar Law',
                'username' => 'trafa',
                'email'    => 'trafa@gmail.com',
                'password' => Hash::make('rahasiakampret'),
            ),
        ));
    }
}

Selanjutnya, buat file seeder baru dengan nama AddressSeeder.php letakkan pada path protected/app/database/seeds/ isi dengan code berikut,
<?php
 
class AddressSeeder extends Seeder
{
    public function run()
    {
        DB::table('addresses')->delete();
        DB::table('addresses')->insert(array (
            array (
                'id' => 1,
                'user_id' => 1,
                'name_address'     => 'Alamat Mihawk',
                'city' => 'north blue',
                'province'    => 'fusa',
                'address' => 'jalan-jalan 1',
                'zipcode' => '12456',
                'phone' => '0982345432',
            ),
            array (
                'id' => 2,
                'user_id' => 2,
                'name_address'     => 'Alamat Law',
                'city' => 'konoha',
                'province'    => 'wano',
                'address' => 'jalan-jalan 2',
                'zipcode' => '12344',
                'phone' => '0987651245',
            ),
        ));
    }
}

Terakhir edit file DatabaseSeeder.php pada path protected/app/database/seeds/ menjadi seperti ini,
<?php

class DatabaseSeeder extends Seeder {

 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
  // Eloquent::unguard();
  DB::statement('SET FOREIGN_KEY_CHECKS=0;');

  $this->call('UserSeeder');
  $this->call('AddressSeeder');

  DB::statement('SET FOREIGN_KEY_CHECKS=1;');
  \Cache::flush();
 }

}

Karena kita menambahkan foreign key maka field database pada phpmyadmin harus di hapus semua terlebih dahulu, caranya seperti ini,

1. Hapus semua field


2. Uncentang Enable foreign key checks


Setelah itu jalankan terminal, masuk path project dan jalankan sintax berikut,


Sehingga hasilnya akan tampak seperti ini,


Pada gambar diatas merupakan tabel addresses jika kita mengklik field user_id maka akan berelasi ke tabel users.

===DONE!===

WHY?
1. Terjadi error foreign key constraint?


Ini terjadi karena format field index anda salah, yang benar adalah integer seperti pada gambar dibawah,


Engine PHP - Upload image beauty code


Pada tutorial sebalumnya kita sudah membuat sebuah engine upload image dengan menggunakan bahasa native PHP tanpa menggunakan class dan function method. Tutorial kali ini kita akan membuat engine yang sama tapi dengan code yang lebih rapi dan terstruktur.

Oke kita mulai saja tutorialnya,
Pertama, buat folder projectnya terlebih dahulu beri nama misal class_method, kemudian buat file index.php pada folder project tersebut dan isikan code berikut,
<form action="save.php" method="post" enctype="multipart/form-data">
    <table width="100%">
        <tr>
            <td><input type="file" name="image"/></td>
        </tr>
        <tr>
            <td>Note: Supported image format: .jpeg, .jpg, .png</td>
        </tr>
    </table>
    <br>
    <input type="submit" value="Save"/>
</form>

Selanjutnya buat file baru dengan nama save.php dan isikan code berikut,
<?php
 Class SaveImage
 {
  public function extensions()
  {
   $extensions = array("jpeg","jpg","png");
   return $extensions;
  }

  public function save()
  {
   $file_name  = $_FILES['image']['name'];
   $file_size  = $_FILES['image']['size'];
   $file_tmp  = $_FILES['image']['tmp_name'];
   $file_ext = strtolower(end(explode('.',$_FILES['image']['name'])));
   $filename  = strtotime('now').'_'.$file_name;
   $error   = '';
   
   if(in_array($file_ext, $this->extensions())=== false){
    $error="extension not allowed, please choose a JPEG or PNG file.";
   }

   if($file_size > 1024000){
    if ($error) {
     $error=$error.' and File size must be excately 1 MB';
    } else {
     $error='File size must be excately 1 MB';
    }
   }

   if(empty($error)==true){
    move_uploaded_file($file_tmp,"images/".$filename);
    $response['status']  = 'Success';
    $response['results'] = $filename;
    return $response;
   }else{
    $response['status']  = 'Error';
    $response['results'] = $error;
    return $response;
   }
  }
 }

 if(isset($_FILES['image'])){
  $save_image = new SaveImage;
  $save = $save_image->save();
  foreach ($save as $key => $value) {
   echo $key.': '.$value.'<br>';
  }
  ?><br><a href="/test/test-upload_image">Back</a><?php
    }
?>

Terakhir buat folder tempat menyimpan image, beri nama folder dengan nama images, sehingga struktur file dan folder akan tampak seperti ini,


Dan tampilan urlnya saat kita akses akan tampak seperti ini,


Terlihat lebih rapi kan dibanding yang native? inilah seni dalam coding..

===DONE!===