-
-
Save eballeste/7b7a04b448f14b269a72a3a1c8b2e75f to your computer and use it in GitHub Desktop.
Laravel Custom Pivot Model Relationships Example (Laravel 7)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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