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!===