Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');     } } 
like image 851
Patrick Reck Avatar asked Oct 20 '14 20:10

Patrick Reck


2 Answers

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');     }  } 
like image 113
c-griffin Avatar answered Sep 25 '22 02:09

c-griffin


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'); 
like image 37
bmatovu Avatar answered Sep 23 '22 02:09

bmatovu