Skip to content

Instantly share code, notes, and snippets.

@lighta971
Created May 9, 2014 15:03
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save lighta971/f2c8e9be27df2ceb5569 to your computer and use it in GitHub Desktop.
Save lighta971/f2c8e9be27df2ceb5569 to your computer and use it in GitHub Desktop.
Laravel Custom Pivot Model definition example
<?php
//https://github.com/laravel/framework/issues/2093#issuecomment-39154456
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Database\Eloquent\Relations\Pivot;
class User extends Eloquent {
public function groups() {
return $this->belongsToMany('Group');
}
public function newPivot(Eloquent $parent, array $attributes, $table, $exists) {
if ($parent instanceof Group) {
return new UserGroup($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
}
class Group extends Eloquent {
public function users() {
return $this->belongsToMany('User');
}
public function newPivot(Eloquent $parent, array $attributes, $table, $exists) {
if ($parent instanceof User) {
return new UserGroup($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
}
class UserGroup extends Pivot {
public function user() {
return $this->belongsTo('User');
}
public function group() {
return $this->belongsTo('Group');
}
// Note: Adding relationships to a pivot model means
// you'll probably want a primary key on the pivot table.
public function posts($value) {
return $this->hasMany('Post'); // example relationship on a pivot model
}
}
@pasha-my-glu
Copy link

nice bro

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment