tzkmx
10/16/2019 - 11:38 AM

Laravel Custom Pivot Model definition example

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
    }
}