;

Selamat Datang di Anggit Prayogo.com

Quality is more important than quantity. One home run is much better than two doubles - Steve Jobs

Many To Many Laravel

Ditulis oleh Anggit Prayogo Wahid Pada 02, Jul 2017 Kategori Sport

Many-to-many relations are slightly more complicated than hasOne and hasMany relationships. An example of such a relationship is a user with many roles, where the roles are also shared by other users. For example, many users may have the role of "Admin". To define this relationship, three database tables are needed: usersroles, and role_user. The role_user table is derived from the alphabetical order of the related model names, and contains the user_id and role_id columns.

Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany method. For example, let's define the roles method on our User model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}

Once the relationship is defined, you may access the user's roles using the roles dynamic property:

$user = App\User::find(1);

foreach ($user->roles as $role) {
    //
}