Laravel - Relationships - Retrieving Intermediate Table Columns

As you have already learned, working with many-to-many relations requires the presence of an intermediate table. Eloquent provides some very helpful ways of interacting with this table. For example, let's assume our User model has many Role models that it is related to. After accessing this relationship, we may access the intermediate table using the pivot attribute on the models:

    
    use App\Models\User;
    
    $user = User::find(1);
    
    foreach ($user->roles as $role) {
        echo $role->pivot->created_at;
    }
	

Notice that each Role model we retrieve is automatically assigned a pivot attribute. This attribute contains a model representing the intermediate table.

By default, only the model keys will be present on the pivot model. If your intermediate table contains extra attributes, you must specify them when defining the relationship:

    
    return $this->belongsToMany(Role::class)->withPivot('active', 'created_by');
	

If you would like your intermediate table to have created_at and updated_at timestamps that are automatically maintained by Eloquent, call the withTimestamps method when defining the relationship:

    
    return $this->belongsToMany(Role::class)->withTimestamps();
	
Intermediate tables that utilize Eloquent's automatically maintained timestamps are required to have both created_at and updated_at timestamp columns.