Skip to content

Instantly share code, notes, and snippets.

@jyhsu2000
Forked from lighta971/pivot_example.php
Created January 24, 2019 10:07
Show Gist options
  • Save jyhsu2000/7b1c072e6a6ade9adff618719ba8171c to your computer and use it in GitHub Desktop.
Save jyhsu2000/7b1c072e6a6ade9adff618719ba8171c 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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment