Skip to content

Instantly share code, notes, and snippets.

@fractefactos
Forked from lighta971/pivot_example.php
Last active October 17, 2022 08:47
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save fractefactos/265063a7a959d1f344e3 to your computer and use it in GitHub Desktop.
Save fractefactos/265063a7a959d1f344e3 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
}
}
@fractefactos
Copy link
Author

Thanks a lot!

Great!

@pasha-my-glu
Copy link

thanks bro its good

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