Eloquent Querying Intermediate Table / Pivot

Add this to the User model.. the new addition is withPivot which allows us to pull data from the intermediate table. We always need to specify this.

    public function roles(){
        return $this->belongsToMany('App\Models\Role')->withPivot('created_at');
    }

Now in routes add this:

Route::get('/user/pivot', function(){
    $user = User::find(1);
    foreach($user->roles as $role){
        echo $role->pivot->created_at;
    }
});

Leave a Reply

Your email address will not be published.