Tutorial Relationship Table di Laravel 8

Tutorial Relationship Table di Laravel 8

Diperbaharui 2 Februari 2021 4:11 AM

Bagaimana cara membuat relasi tabel di laravel? One to one, One to Many, Many to Many? Berikut adalah tutorial relationship table di laravel 8. Silakan Anda baca terlebih dahulu pengertian dari masing-masing elequent: relationships yang sering digunakan saat menggunakan laravel.

Apa itu relasi One to one?

One to one relationship adalah kondisi dimana data dari tabel A hanya boleh memiliki satu data dari tabel B (A hasOne B) dan data dari tabel B hanya boleh dimiliki oleh satu data di tabel A (B belongsTo A).

Contoh kasus :

Terdapat 2 model yaitu User dan Phone yang mewakili tabel users dan phones, untuk tabel users menggunakan struktur tabel default dari laravel sedangkan untuk phone hanya menambahkan foreignId dan nomor handpone.

1 user hanya boleh memiliki 1 nomor, dan 1 nomor hanya boleh dimiliki oleh 1 user

Mari kita buat project baru khusus untuk memahami relationships table pada laravel 8, silakan jalankan perintah berikut di terminal pada folder laravel :

laravel new laravel-8-relationships
cd laravel-8-relationships
code .
composer require laravel/breeze --dev
php artisan breeze:install
npm install && npm run dev

Jangan lupa untuk mengatur database pada file .env, sesuaikan username dan password serta buat database yang sesuai dengan nama database pada file .env. Maka sekarang project laravel sudah siap digunakan, mari kita mulai membuat contoh relasi pada laravel.

1. Pertama jalankan perintah berikut :

php artisan make:controller UserController
php artisan make:controller PhoneController -i
php artisan make:model Phone -m
php artisan make:factory PhoneFactory

Keterangan :

  • Membuat controller untuk user
  • Membuat controller untuk phone dimana cukup membuat 1 fungsi yaitu __invoke
  • Membuat model phone sekaligus dengan migration nya
  • Membuat data dummy dengan factory

2. Buka app/Http/Controllers/UserController.php dan tambahkan function berikut :

use App\Models\User;

public function oneToOne()
{
    return view('one-to-one.users', [
        'title' => 'One to One User',
        'users' => User::get(),
    ]);
}

3. Buka app/Http/Controllers/PhoneController.php dan ubah function __invoke menjadi kode berikut :

use App\Models\Phone;

public function __invoke()
{
    return view('one-to-one.phones', [
        'title'  => 'One to One User',
        'phones' => Phone::get(),
    ]);
}

4. Buka database/migrations/xxx_create_phones_table.php dan tambahkan field seperti pada kode berikut :

public function up()
{
    Schema::create('phones', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id')->unique();
        $table->string('phone_number')->unique();
        $table->timestamps();

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

5. Buka database/factories/PhoneFactory.php :

public function definition()
{
    return [
        'user_id'      => $this->faker->unique()->numberBetween(1, 5),
        'phone_number' => $this->faker->unique()->phoneNumber,
    ];
}

Keterangan :

  • user_id dibuat dari nomor 1 sampai 5 menggunakan faker dan unik karena nantinya hanya akan 5 user yang dibuat
  • phone_number dibuat menggunakan faker phoneNumber
  • Silakan baca tutorial tentang Cara Membuat Seeder Factory di Laravel 8

6. Buka database/seeders/DatabaseSeeder.php :

use App\Models\User;
use App\Models\Phone;

public function run()
{
    ...
    User::factory(5)->create();
    Phone::factory(5)->create();
}

Karena setiap model sudah menggunakan HasFactory sehingga bisa dipanggil dari seeder dimana membuat 5 data user dan 5 data phone.

php artisan migrate --seed

Kemudian tinggal menggunakan fungsi relasi dari laravel sehingga bisa memanggil data dari tabel lain.

7. Buka app/Models/User.php dan tambahkan kode berikut :

public function phone()
{
    return $this->hasOne(Phone::class);
}

8. Buka app/Models/Phone.php dan tambahkan kode berikut :

public function user()
{
    return $this->belongsTo(User::class);
}

Sekarang jika Anda ingin memanggil nomor handphone dari tabel user cukup tambahkan phone->phone_number maka data dari tabel phones bisa terpanggil.

9. Buka routes/web.php dan tambahkan route untuk menampilkan data :

use App\Http\Controllers\UserController;
use App\Http\Controllers\PhoneController;

Route::get('one-to-one/users', [UserController::class, 'oneToOne'])->name('oneToOneUsers');
Route::get('one-to-one/phones', PhoneController::class)->name('oneToOnePhones');

10. Buat file resources/views/one-to-one/users.blade.php :

@foreach ($users as $user)
<ul>
    <li>{{ $user->name }}</li>
    <li>{{ $user->phone->phone_number }}</li>
</ul>
@endforeach

11. Buat file resources/views/one-to-one/phones.blade.php :

@foreach ($phones as $phone)
<ul>
    <li>{{ $phone->phone_number }}</li>
    <li>{{ $phone->user->name }}</li>
</ul>
@endforeach

Silakan cek :

  • http://laravel-8-relationships.test/one-to-one/users
  • http://laravel-8-relationships.test/one-to-one/phones
One to One Relationship Table

Apa itu relasi One to many?

One to many relationship adalah kondisi dimana data dari tabel A boleh memiliki lebih dari satu data dari tabel B (A hasMany B) dan data dari tabel B hanya boleh dimiliki oleh satu data dari tabel A (B belongsTo A).

Contoh kasus :

1 user boleh memiliki lebih dari 1 nomor, 1 nomor hanya boleh dimiliki 1 user

1. Buat controller, model dan factory baru untuk phone dengan mengetikkan kode berikut :

php artisan make:controller PhoneManyController -i
php artisan make:model PhoneMany -m
php artisan make:factory PhoneManyFactory

2. Buka app/Http/Controllers/UserController.php dan tambahkan kode berikut :

public function oneToMany()
{
    return view('one-to-many.users', [
        'title' => 'One to Many User',
        'users' => User::get(),
    ]);
}

3. Buka app/Http/Controllers/PhoneManyController.php :

use App\Models\PhoneMany;

public function __invoke()
{
    return view('one-to-many.phones', [
        'title'  => 'One to Many Phone',
        'phones' => PhoneMany::get(),
    ]);
}

4. Buka database/migrations/xxx_create_phone_manies_table.php :

public function up()
{
    Schema::create('phone_manies', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id');
        $table->string('phone_number')->unique();
        $table->timestamps();

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

5. Buka database/factories/PhoneManyFactory.php :

public function definition()
{
    return [
        'user_id'      => $this->faker->numberBetween(1, 5),
        'phone_number' => $this->faker->unique()->phoneNumber,
    ];
}

6. Buka database/seeders/DatabaseSeeder.php :

use App\Models\PhoneMany;

public function run()
{
    ...
    PhoneMany::factory(10)->create();
}
php artisan migrate:fresh --seed

7. Buka app/Models/User.php :

public function phones()
{
    return $this->hasMany(PhoneMany::class);
}

8. Buka app/Models/PhoneMany.php :

public function user()
{
    return $this->belongsTo(User::class);
}

9. Buka routes/web.php :

use App\Http\Controllers\PhoneManyController;

Route::get('one-to-many/users', [UserController::class, 'oneToMany'])->name('oneToManyUsers');
Route::get('one-to-many/phones', PhoneManyController::class)->name('oneToManyPhones');

10. Buat file resources/views/one-to-many/users.blade.php :

@foreach ($users as $user)
<ul>
    <li>{{ $user->name }}</li>
    <ol>
        @foreach ($user->phones as $phone)
        <li>{{ $phone->phone_number }}</li>
        @endforeach
    </ol>
</ul>
@endforeach

11. Buat file resources/views/one-to-many/phones.blade.php :

@foreach ($phones as $phone)
<ul>
    <li>{{ $phone->phone_number }}</li>
    <li>{{ $phone->user->name }}</li>
</ul>
@endforeach

Silakan cek :

  • http://laravel-8-relationships.test/one-to-many/users
  • http://laravel-8-relationships.test/one-to-many/phones
One to Many Relation User

Apa itu relasi many to many?

Many to many relationship adalah kondisi dimana data dari tabel A boleh memiliki banyak data dari tabel B (A hasMany B) dan data dari tabel B boleh dimiliki oleh banyak data dari tabel A (B belongsToMany A).

Contoh kasus :

1 user boleh mempunyai banyak hobi, 1 hobi boleh dimiliki oleh banyak user

1. Seperti biasa buat terlebih dahulu controller, model dan data dummy :

php artisan make:controller HobbyController -i
php artisan make:model Hobby -m
php artisan make:seeder HobbySeeder

2. Buka app/Http/Controllers/UserController.php :

public function manyToMany()
{
    return view('many-to-many.users', [
        'title' => 'Many to Many User',
        'users' => User::get(),
    ]);
}

3. Buka app/Http/Controllers/HobbyController.php :

use App\Models\Hobby;

public function __invoke()
{
    return view('many-to-many.hobbies', [
        'title'   => 'Many to Many Hobby',
        'hobbies' => Hobby::get(),
    ]);
}

4. Buka database/migrations/xxx_create_hobbies_table.php :

public function up()
{
    Schema::create('hobbies', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->text('description')->nullable();
        $table->timestamps();
    });
}

5. Buka database/seeders/HobbySeeder.php

use App\Models\Hobby;

public function run()
{
    $hobbies = [
        'Renang',
        'Membaca',
        'Editing Video',
        'Koding',
        'Rebahan',
        'Makan',
        'Tidur',
        'Menembak',
        'Badminton',
        'Voli',
    ];

    foreach ($hobbies as $value) {
        Hobby::create([
            'name' => $value,
        ]);
    }
}

Karena kita akan membuat relasi many to many maka kita memerlukan pivot table, yaitu sebagai tabel penampung dari 2 tabel. Di dalam pivot table mempunyai primary key dari masing-masing tabel yang berelasi.

php artisan make:migration create_hobby_user_table

Setiap kali ingin membuat pivot table maka urutannya harus abjad, dalam hal ini (h)obby berada di urutan pertama dan (u)ser berada setelahnya.

6. Buka database/migrations/xxx_create_hobby_user_table.php :

public function up()
{
    Schema::create('hobby_user', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id');
        $table->foreignId('hobby_id');

        $table->timestamps();

        $table->foreign('user_id')->references('id')->on('users');
        $table->foreign('hobby_id')->references('id')->on('hobbies');
    });
}

7. Untuk memudahkan dalam pembuatan data dummy maka kita buat factory saja :

php artisan make:model HobbyUser
php artisan make:factory HobbyUserFactory

8. Buka app/Models/HobbyUser.php :

class HobbyUser extends Model
{
    use HasFactory;

    protected $table      = 'hobby_user';
    protected $primaryKey = 'id';

    protected $guarded = [];
}

9. Buka database/factories/HobbyUserFactory.php :

public function definition()
{
    return [
        'user_id'  => $this->faker->numberBetween(1, 5),
        'hobby_id' => $this->faker->numberBetween(1, 10),
    ];
}

10. Buka database/seeders/DatabaseSeeder.php :

use App\Models\HobbyUser;

public function run()
{
    ...
    $this->call(HobbySeeder::class);
    HobbyUser::factory(10)->create();
}
php artisan migrate:fresh --seed

11. Buka app/Models/User.php :

public function hobbies()
{
    return $this->belongsToMany(Hobby::class);
}

12. Buka app/Models/Hobby.php :

public function users()
{
    return $this->belongsToMany(User::class);
}

13. Sekarang buat view nya, silakan buat file resources/views/many-to-many/users.blade.php :

@foreach ($users as $user)
<ul>
    <li>{{ $user->name }}</li>
    <ol>
        @foreach ($user->hobbies as $hobby)
        <li>{{ $hobby->name }}</li>
        @endforeach
    </ol>
</ul>
@endforeach

14. Buat file resources/views/many-to-many/hobbies.blade.php :

@foreach ($hobbies as $hobby)
<ul>
    <li>{{ $hobby->name }}</li>
    <ol>
        @foreach ($hobby->users as $user)
        <li>{{ $user->name }}</li>
        @endforeach
    </ol>
</ul>
@endforeach

15. Terakhir buat route, buka routes/web.php :

use App\Http\Controllers\HobbyController;

Route::get('many-to-many/users', [UserController::class, 'manyToMany'])->name('manyToManyUsers');
Route::get('many-to-many/hobbies', HobbyController::class)->name('manyToManyHobbies');

Silakan cek :

  • http://laravel-8-relationships.test/many-to-many/users
  • http://laravel-8-relationships.test/many-to-many/hobbies
Many to Many Relation Laravel
Many to Many Relation Table

Itulah artikel tentang tutorial relationship table di laravel 8 yang dapat saya sampaikan, semoga bermanfaat.

susantokun avatar
susantokun
Hanya seorang programmer yang fokus di bidang web development. Tidak nyaman dengan keramaian dan suka akan keindahan.
Kebijakan Berkomentar :
1. Dilarang berkomentar yang mengandung SPAM, SARA, HOAX, PORNO.2. Mohon sertakan informasi detail saat terjadi error (pesan error, sreenshoot, code, logs, dsb.).