Skip to content

Instantly share code, notes, and snippets.

@eballeste
Forked from lighta971/pivot_example.php
Last active August 26, 2020 05:39
Show Gist options
  • Save eballeste/7b7a04b448f14b269a72a3a1c8b2e75f to your computer and use it in GitHub Desktop.
Save eballeste/7b7a04b448f14b269a72a3a1c8b2e75f to your computer and use it in GitHub Desktop.
Laravel Custom Pivot Model Relationships Example (Laravel 7)
<?php
// https://github.com/laravel/framework/issues/2093#issuecomment-28689244
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;
class User extends Model {
public function groups() {
return $this->belongsToMany(Group::class)
->using(GroupUser::class);
}
}
class Group extends Model {
public function users() {
return $this->belongsToMany(User::class)
->using(GroupUser::class);
}
}
class GroupUser extends Pivot {
public function user() {
return $this->belongsTo(User::class);
}
public function group() {
return $this->belongsTo(Group::class);
}
// 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::class); // example relationship on a pivot model
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment