How to get values from pivot table in laravel?

by lindsey.homenick , in category: PHP Frameworks , 5 months ago

How to get values from pivot table in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 5 months ago

@lindsey.homenick 

To get values from a pivot table in Laravel, you can use the withPivot method when defining the relationship in your model.


For example, if you have a many-to-many relationship between User and Role models with a pivot table role_user, and you want to get additional information from the pivot table, you can define the relationship like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// User model
class User extends Model {
    public function roles() {
        return $this->belongsToMany(Role::class)->withPivot('created_at', 'updated_at');
    }
}

// Role model
class Role extends Model {
    public function users() {
        return $this->belongsToMany(User::class)->withPivot('created_at', 'updated_at');
    }
}


Now, when you access the pivot table through the relationship, you can access the additional pivot table columns like this:

1
2
3
4
5
$user = User::find(1);
foreach($user->roles as $role) {
    echo $role->pivot->created_at;
    echo $role->pivot->updated_at;
}


This way, you can retrieve and use the values from the pivot table in Laravel.