43

I have two models, User and Badge. A user can have multiple badges, and a badge can belong to multiple users. (using a pivot table)

Currently I am getting the data I need, but additionally I am getting the pivot table along. How do I exclude this?

enter image description here

Here's the User model:

class User extends Eloquent {

    public function badges() {
        return $this->belongsToMany('Badge', 'users_badges');
    }

}

And the Badge model:

class Badge extends Eloquent {

    public function users() {
        return $this->belongsToMany('User', 'users_badges');
    }
}
Patrick Reck
  • 11,246
  • 11
  • 53
  • 86

2 Answers2

87

Add pivot to your $hidden property's array in your model(s).

class Badge extends Eloquent {

    protected $hidden = ['pivot'];

    public function users() {
        return $this->belongsToMany('User', 'users_badges');
    }
}

And same with your User model

class User extends Eloquent {

    protected $hidden = ['pivot'];

    public function badges() {
        return $this->belongsToMany('Badge', 'users_badges');
    }

}
c-griffin
  • 2,938
  • 1
  • 18
  • 25
  • 2
    @challet Yes, check out [the documentation here](https://laravel.com/docs/5.6/eloquent-serialization#hiding-attributes-from-json). Scroll a little bit down and you will find an example of how to dynamically hide attributes. – ba0708 Apr 19 '18 at 11:14
  • Note if you omit one model this will not work. You must hide the pivot on both related models. – topvova Dec 03 '22 at 02:17
39

Or you can still hide the pivot on demand this way...

$user = User::find(1);
$user->badges->makeHidden('pivot');

$badge = Badge::find(1);
$badge->users->makeHidden('pivot');
bmatovu
  • 3,756
  • 1
  • 35
  • 37
  • 1
    `makeHidden` and `makeVisible` accept arrays as well: `makeHidden(['pivot', 'id', ...])` or `makeVisible(['pivot', 'id', ...])` – user8555937 Dec 20 '19 at 13:07