# Membuat Eloquent Many to Many Laravel 8

<figure><img src="https://3397141630-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVUQUm1GVUT3pDnRHmDRU%2Fuploads%2FUFYHV814mSP3ArUMrW0B%2FUntitled.png?alt=media&#x26;token=8512c5cb-c19a-4616-bb79-3cf18c3ea09e" alt=""><figcaption></figcaption></figure>

saya mau buat many to many di Laravel 8

Langsung aja ya..

Struktur Table seperti ini:

```
users
    id - integer
    name - string

roles
    id - integer
    name - string

role_user
    user_id - integer
    role_id - integer
```

Buat hanya 2 model saja, 1 table sebagai penghubung dari 2 table yang ada model nya.

```
php artisan make:model Role -m
```

Jika model user sudah ada tidak perlu buat lagi, karena biasanya ketika install awal project laravel 8 UI sudah disertain dengan table user.

Tambahkan table tanpa membuat model baru sbb:

```
php artisan make:migration create_role_user_table --name=role_user
```

Kemudian, masukan id dari table user & role sebagai foreign key sbb:

```
public function up()
    {
        Schema::create('role_user', function (Blueprint $table) {
            $table->unsignedInteger('user_id');
            $table->bigInteger('role_id')->unsigned();

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

```

Pada model User buat seperti ini:

```
class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
    }
}
```

Pada model Role buat seperti ini:

```
classRoleextendsModel{/**
     * The users that belong to the role.
     */publicfunctionusers(){
        return $this->belongsToMany(User::class, 'role_user', 'user_id', 'role_id');}}
```

Contoh hasilnya:

<figure><img src="https://3397141630-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVUQUm1GVUT3pDnRHmDRU%2Fuploads%2Fa2YThTQTcH8Ti1kQYwz2%2FUntitled%20(1).png?alt=media&#x26;token=e5eaf368-d9b6-4b0e-b4ff-15ada41e6f15" alt=""><figcaption></figcaption></figure>

Noted: gambar ini dengan table yg berbeda kasus hanya saja mirip

Sekian, Gomawo^^
