menu

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