Patrick Reck
Patrick Reck

Reputation: 11374

Laravel belongsToMany exclude pivot table

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');
    }
}

Upvotes: 45

Views: 34775

Answers (2)

bmatovu
bmatovu

Reputation: 4074

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');

Upvotes: 42

c-griffin
c-griffin

Reputation: 3026

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');
    }

}

Upvotes: 93

Related Questions