Kali ini kita akan membahas contoh penggunaan relasi Laravel Eloquent satu ke satu.

Buat Migration

php artisan make:model UserDetails -m
# output
Model created successfully.
Created Migration: 2017_11_21_032155_create_user_details_table

Semua file migration berada di folder database/migrations/, edit file migration xxx_create_users_table.php, ubah menjadi

public function up()
{
  Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->integer('user_details_id')->unsigned();
    $table->rememberToken();
    $table->timestamps();
  });
}

edit file xxxx_create_user_details_table.php

public function up()
{
  Schema::create('user_details', function (Blueprint $table) {
    $table->increments('id');
    $table->string('nomor_hp');
    $table->text('alamat');
    $table->timestamps();
  });
}

lalu jalankan migration

php artisan migrate

Buat Model

Edit model file app/UserDetail.php

class UserDetail extends Model
{
    protected $table = 'user_details';
    protected $fillable = ['nomor_hp', 'alamat'];
}

Buat Database Seed

Kita akan membuat database seed untuk membuat data dummy, sebagai contoh di database

php artisan make:seeder UsersTableSeeder
php artisan make:seeder UserDetailsTableSeeder

file seeder berada di folder database/seeds

Edit file UserDetailsTableSeeder.php

<?php
 
use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
 
class UserDetailsTableSeeder extends Seeder
{
    public function run()
    {
        $faker = Faker::create();
        foreach(range(1, 10) as $index)
        {
            App\UserDetail::create([
                'nomor_hp' => $faker->phoneNumber,
                'alamat' => $faker->address,
            ]);
        }
    }
}

Edit file UsersTableSeeder.php

<?php
 
use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
 
class UsersTableSeeder extends Seeder
{
    public function run()
    {
        $faker = Faker::create();
        foreach(range(1, 10) as $index)
        {
            App\User::create([
                'name' => $faker->name,
                'email' => $faker->unique()->safeEmail,
                'password' => bcrypt('secret'),
                'user_details_id' => mt_rand(1,10),
                'remember_token' => str_random(10),
            ]);
        }
    }
}

lalu jalankan database seed

php artisan db:seed --class=UserDetailsTableSeeder
php artisan db:seed --class=UsersTableSeeder

Buat Controller

php artisan make:controller UserController

edit file UserController.php

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use App\User;
 
class UserController extends Controller
{
    public function index() {
        $users = User::all();
 
        return view('welcome', compact('users'));
    }
}

Relasi Antar Tabel

Edit file app/User.php yang tadi telah dibuat dibawah

    protected $hidden = [
        'password', 'remember_token',
    ];

tambahkan

    public function user_details() {
        return $this->belongsTo('App\UserDetail');
    }

Bila anda menggunakan tabel dengan underscore contoh nama_tabel relasinya harus dibuat dengan format nama_tabel juga, kalo ngga anda harus menambahkan foreign key dan local key secara manual

contoh

    public function userdetails() {
        return $this->belongsTo('App\UserDetails', 'user_details_id', 'id');
    }

bandingkan dengan relasi yang dibuat diatas.

View

edit file resources/views/welcome.blade.php

<!doctype html>
<html lang="en">
<head>
    <title>Relation One to One - Jaranguda.com</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
</head>
<body>
 
    <main role="main" class="container">
        <div class="col-md-12">
            <h3>Database Relation</h3>
 
                <table class="table table-hover table-striped table-bordered">
                    <thead>
                        <tr>
                            <th scope="col">Name</th>
                            <th scope="col">Email</th>
                            <th scope="col">Nomor HP</th>
                            <th scope="col">Alamat</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($users as $user)
                            <tr>
                                <td>{{ $user->name }}</td>
                                <td>{{ $user->email }}</td>
                                <td>{{ $user->user_details->nomor_hp }}</td>
                                <td>{{ $user->user_details->alamat }}</td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
        </div>
    </main>
</body>
</html>

Ubah routes

Edit file routes/web.php

<?php
 
Route::get('/', 'UserController@index');

Tampilan

tampilan relasi one to one laravel

Leave a comment

Your email address will not be published. Required fields are marked *