implement many to many relationship laravel eloquent code example

Example 1: many to many relationship laravel

use App\Models\User;

$user = User::find(1);

$user->roles()->attach($roleId);

Example 2: laravel many to many relationship

/*
users
    id - integer
    name - string

roles
    id - integer
    name - string

role_user
    user_id - integer
    role_id - integer
*/

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
      /*To determine the table name of the relationship's intermediate 
      table, Eloquent will join the two related model names in 
      alphabetical order. However, you are free to override this 
      convention. You may do so by passing a second argument to the 
      belongsToMany method*/
        return $this->belongsToMany(Role::class,'role_user');
    }
}
//Defining The Inverse Of The Relationship

class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany(User::class);
    }
}

Example 3: add data to laravel many to many relationship

1. $user->roles()->attach($roleId);

2. you may also pass an array of additional data to be inserted 
$user->roles()->attach($roleId, ['expires' => $expires]);

3. // Detach a single role from the user...
$user->roles()->detach($roleId);

4. // Detach all roles from the user...
$user->roles()->detach();

5. Any IDs that are not in the given array will be removed from the intermediate
	table
$user->roles()->sync([1, 2, 3]);

6. If you need to update an existing row in your pivot table, you may use 
  updateExistingPivot method. This method accepts the pivot record foreign 
  key and an array of attributes to update:

$user->roles()->updateExistingPivot($roleId, $attributes);

Tags:

Php Example