Laravel: 5.8.32
PHP: 7.3.7
Many-to-Many relationship, Company has many Users and vice versa, User can belong to many Companies, the intermediate table is called Access (table: accesses).
Company:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
public function users() {
return $this->belongsToMany('App\User')
->using('App\Access')
->withPivot('type', 'permissions')
->as('access')
->withTimestamps();
}
}
User:
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $fillable = ['email', 'password', 'first_name', 'last_name'];
protected $hidden = ['password'];
public function companies() {
return $this->belongsToMany('App\Company', 'accesses')
->as('access')
->withTimestamps();
}
}
Intemediate Table - Access:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;
class Access extends Pivot
{
protected $table = 'accesses';
protected $casts = [
'manage_billing' => 'boolean'
];
}
Steps to reproduce bug:
You need to specify the custom pivot table as the second argument:
class Company extends Model
{
public function users() {
return $this->belongsToMany('App\User', 'accesses')
->using('App\Access') ^^^^^^^^^^
->withPivot('type', 'permissions')
->as('access')
->withTimestamps();
}
}
You can also provide the pivot class as the second argument and remove using():
class Company extends Model
{
public function users() {
return $this->belongsToMany('App\User', 'App\Access')
^^^^^^^^^^^^
->withPivot('type', 'permissions')
->as('access')
->withTimestamps();
}
}
Thanks, your recommendation seems to be working for me. Closing.
Most helpful comment
You need to specify the custom pivot table as the second argument:
You can also provide the pivot class as the second argument and remove
using():