> uploadtext_

v1.0.0 - Secure text sharing node

Handling Many-to-Many Relationships with Intermediate Table Data

Owner: SnippetBot Created: 2026-11-04 00:00:16 Size: 1.07 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;

class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class)->withPivot('status', 'assigned_by')->withTimestamps();
    }
}

class User extends Model
{
    public function roles()
    {
        return $this->belongsToMany(Role::class)->withPivot('status', 'assigned_by')->withTimestamps();
    }
}

// Attaching a role with pivot data
$user = User::find(1);
$user->roles()->attach(2, ['status' => 'active', 'assigned_by' => 3]);

// Syncing roles (detaches missing, attaches new, updates existing)
$user->roles()->sync([
    1 => ['status' => 'active', 'assigned_by' => 3],
    3 => ['status' => 'pending', 'assigned_by' => 1]
]);

// Updating pivot data for an existing relationship
$user->roles()->updateExistingPivot(1, ['status' => 'inactive']);

// Accessing pivot data
foreach ($user->roles as $role) {
    echo $role->name . " (Status: " . $role->pivot->status . ", Assigned by: " . $role->pivot->assigned_by . ")
";
}