Days
Hours
Minutes
Seconds

Promo Grand Opening

15% OFF

Khusus Pelanggan Baru

Tutorial Laravel #23 : Relasi One To One Laravel

 

 

Dalam pengembangan aplikasi web, relasi antar tabel di database adalah konsep yang sangat umum. Laravel Eloquent ORM mempermudah pengelolaan relasi ini. Pada tutorial kali ini, kita akan fokus pada jenis relasi One To One (Satu ke Satu).

Relasi one to one menggambarkan hubungan di mana satu model (baris data dalam tabel) berkorespondensi tepat dengan satu model lain (baris data dalam tabel lain), dan sebaliknya. Contoh umumnya adalah relasi antara user dan profil pengguna, di mana setiap user memiliki satu profil, dan setiap profil dimiliki oleh satu user.


 

Persiapan Awal

 

Pastikan Anda sudah memiliki hal-hal berikut:

  1. Proyek Laravel: Proyek Laravel Anda sudah berjalan dan terhubung ke database.
  2. Migration untuk Tabel: Kita akan membuat dua tabel: users dan profiles. Jika Anda sudah memiliki tabel users, Anda bisa membuat migration hanya untuk tabel profiles.

    Migration untuk Tabel users (jika belum ada):

    “`bash

    php artisan make:migration create_users_table –create=users

    “`

    Modifikasi file migration create_users_table:

    “`php

    public function up()

    {

    Schema::create(‘users’, function (Blueprint $table) {

    $table->id();

    $table->string(‘name’);

    $table->string(’email’)->unique();

    $table->timestamp(’email_verified_at’)->nullable();

    $table->string(‘password’);

    $table->rememberToken();

    $table->timestamps();

    });

    }

    “`

    Migration untuk Tabel profiles:

    “`bash

    php artisan make:migration create_profiles_table –create=profiles

    “`

    Modifikasi file migration create_profiles_table:

    “`php

    public function up()

    {

    Schema::create(‘profiles’, function (Blueprint $table) {

    $table->id();

    $table->unsignedBigInteger(‘user_id’)->unique(); // Foreign key ke tabel users, memastikan one-to-one

    $table->string(‘alamat’)->nullable();

    $table->string(‘nomor_telepon’)->nullable();

    $table->date(‘tanggal_lahir’)->nullable();

    $table->timestamps();

        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
    

    }

    public function down()

    {

    Schema::dropIfExists(‘profiles’);

    }

    “`

    Jalankan migration: php artisan migrate

  3. Model: Buat dua model yang sesuai: User dan Profile.

    “`bash

    php artisan make:model User

    php artisan make:model Profile

    “`


 

Langkah 2: Mendefinisikan Relasi di Model

 

Sekarang, kita definisikan relasi one to one di kedua model.

 

Model User.php (app/Models/User.php)

 

Tambahkan method profile() yang mendefinisikan relasi dengan model Profile.

“`php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Notifications\Notifiable;

use Laravel\Sanctum\HasApiTokens;

use Illuminate\Database\Eloquent\Relations\HasOne;

class User extends Authenticatable

{

use HasApiTokens, HasFactory, Notifiable;

// ... (properti lain dari model User) ...

/\*\*
 \* Get the user's profile.
 \*/
public function profile(): HasOne
{
    return $this->hasOne(Profile::class);
}

}

“`

  • hasOne(Profile::class): Method ini menunjukkan bahwa satu User memiliki satu Profile. Eloquent secara otomatis akan mencari kolom user_id di tabel profiles berdasarkan konvensi nama.

 

Model Profile.php (app/Models/Profile.php)

 

Tambahkan method user() yang mendefinisikan relasi kebalikannya dengan model User.

“`php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Profile extends Model

{

use HasFactory;

protected $fillable = ['user_id', 'alamat', 'nomor_telepon', 'tanggal_lahir'];

/\*\*
 \* Get the user that owns the profile.
 \*/
public function user(): BelongsTo
{
    return $this->belongsTo(User::class);
}

}

“`

  • belongsTo(User::class): Method ini menunjukkan bahwa satu Profile dimiliki oleh satu User. Eloquent secara otomatis akan mencari kolom user_id di tabel profiles.

 

Langkah 3: Berinteraksi dengan Relasi One To One

 

Sekarang kita bisa berinteraksi dengan relasi ini di controller atau tinker.

 

Membuat Data dengan Relasi

 

“`php

use App\Models\User;

use App\Models\Profile;

// Membuat user baru dan profilnya sekaligus

$user = User::create([‘name’ => ‘John Doe’, ’email’ => ‘john.doe@example.com’, ‘password’ => bcrypt(‘secret’)]);

$profile = new Profile([‘alamat’ => ‘Jl. Contoh No. 123’, ‘nomor_telepon’ => ‘08123456789’, ‘tanggal_lahir’ => ‘1990-01-01’]);

$user->profile()->save($profile);

// Atau, jika Anda sudah memiliki user:

$user = User::find(1);

$profile = new Profile([‘alamat’ => ‘Alamat Baru’, ‘nomor_telepon’ => ‘08987654321’, ‘tanggal_lahir’ => ‘1995-05-10’]);

$user->profile()->save($profile);

// Cara lain (mass assignment, pastikan $fillable di model Profile sudah diisi):

$user = User::find(2);

$user->profile()->create([‘alamat’ => ‘Alamat Lain’, ‘nomor_telepon’ => ‘08567890123’, ‘tanggal_lahir’ => ‘1988-12-25’]);

“`

 

Mengambil Data dengan Relasi (Eager Loading)

 

Untuk menghindari masalah N+1 query, gunakan eager loading dengan method with().

“`php

// Mengambil semua user beserta profilnya

$users = User::with(‘profile’)->get();

foreach ($users as $user) {

echo “Nama: ” . $user->name . “<br>”;

echo “Alamat: ” . $user->profile->alamat . “<br><br>”;

}

// Mengambil satu user beserta profilnya

$user = User::with(‘profile’)->find(1);

echo “Nama: ” . $user->name . “<br>”;

echo “Nomor Telepon: ” . $user->profile->nomor_telepon . “<br>”;

“`

 

Mengakses Relasi Sebagai Properti Dinamis

 

Anda juga bisa mengakses relasi sebagai properti dinamis.

“`php

$user = User::find(1);

echo “Tanggal Lahir: ” . $user->profile->tanggal_lahir . “<br>”;

$profile = Profile::find(1);

echo “Nama User: ” . $profile->user->name . “<br>”;

“`

 

Memperbarui Data dengan Relasi

 

“`php

$user = User::find(1);

$user->profile->alamat = ‘Alamat yang Diperbarui’;

$user->profile->save();

// Atau menggunakan method update pada relasi:

$user = User::find(2);

$user->profile()->update([‘nomor_telepon’ => ‘08112233445’]);

“`

 

Menghapus Data dengan Relasi (Cascade Delete)

 

Jika Anda ingin menghapus profil secara otomatis saat user dihapus, pastikan Anda mengatur onDelete('cascade') pada definisi foreign key di migration tabel profiles.

“`php

// Di migration create_profiles_table:

$table->foreign(‘user_id’)->references(‘id’)->on(‘users’)->onDelete(‘cascade’);

“`

Kemudian, saat Anda menghapus user:

“`php

$user = User::find(1);

$user->delete(); // Profil user dengan user_id 1 juga akan terhapus

“`


 

Kesimpulan

 

Relasi One To One di Laravel Eloquent mempermudah pengelolaan hubungan antara dua model yang saling berkorespondensi. Dengan definisi yang tepat di model dan penggunaan eager loading, Anda dapat dengan efisien mengambil dan memanipulasi data yang saling terkait. Pemahaman relasi ini sangat penting dalam membangun aplikasi web yang kompleks dan terstruktur dengan Laravel.

Wawasan Terbaru

Gemini_Generated_Image_wfw5uwwfw5uwwfw5
Mengenal Dunia Grafis: Dari Piksel Hingga Vektor, Kekuatan Visual di Era Digital
Gemini_Generated_Image_b6dimfb6dimfb6di
Mengenal Foundation: Kerangka Kerja Front-End Profesional untuk Web Responsif
Gemini_Generated_Image_sx3ztpsx3ztpsx3z
CSS
Mempercantik Website dengan CSS: Seniman di Balik Tampilan Web 🎨
Gemini_Generated_Image_e013qke013qke013
Mengenal HTML: Fondasi dari Setiap Halaman Website 🌐
Gemini_Generated_Image_ldki4nldki4nldki
Menyelami Dunia Coding: Seni Berbicara dengan Komputer
Gemini_Generated_Image_dpvliydpvliydpvl
Menguasai GIT: Fondasi Penting dalam Dunia Pengembangan Perangkat Lunak
Gemini_Generated_Image_sqcib9sqcib9sqci
Tutorial Python #12: Mengenal Jenis-jenis Operator dalam Python
Gemini_Generated_Image_o1bw3do1bw3do1bw
Memahami Tipe Data Dictionary dalam Python
Gemini_Generated_Image_ko4ixfko4ixfko4i
Mengenal Tipe Data Set dalam Python
Gemini_Generated_Image_1xop7m1xop7m1xop
Tuple dalam Python: Pengenalan dan Tutorial

Wawasan Serupa

Gemini_Generated_Image_q0o3sbq0o3sbq0o3
Gemini_Generated_Image_mem6cgmem6cgmem6
Gemini_Generated_Image_ust09gust09gust0
Gemini_Generated_Image_d8a5kwd8a5kwd8a5

Ceritakan Detail Proyekmu

Mulai dari 30K aja, solusi IT kamu langsung jalan tanpa drama.

Kata Mereka Tentang Solusi Coding

Dipercaya oleh lebih dari 200++ client untuk menyelesaikan proyeknya dengan total 250++ proyek dari berbagai jenis proyek