$this->belongsToMany should only be used when you have a pivot table.
For this a Student belongs to many schools and school belongs to many Student
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi - I can't figure out what is going wrong with this set up which is resulting in a null value being sent on an attach request. I have a school/student many-to-many relationship with these models
class School extends Model{
public function students()
{
return $this->belongsToMany('App\Student', 'school_student', 'school_id', 'student_user_id');
}
}
class Student extends Model
{
protected $primaryKey = 'user_id';
public function schools()
{
return $this->belongsToMany(School::class);
}
}
and this Controller->store()
public function store(\App\Http\Requests\StudentAddSchoolStoreRequest $request)
{
$student = new Student();
$student->id = auth()->user()->id;
$school = new School();
$school->id = $request->id;
$student->schools()->attach($request->id);
return redirect('school')->with('message', 'Successful update!');
}
The attach command generates: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'student_user_id' cannot be null (SQL: insert into school_student (school_id, student_user_id) values (5320, ?))
However, it runs successfully if I substitute 'User' in place of Student
class User extends Authenticatable
{
use Notifiable;
public function schools()
{
return $this->belongsToMany(School::class,'school_student','school_id', 'student_user_id');
}
}
public function store(\App\Http\Requests\StudentAddSchoolStoreRequest $request)
{
//StudentAddSchoolStoreRequest handles validation and error processing
$user = new User();
$user->id = auth()->user()->id;
$school = new School();
$school->id = $request->id;
$user->schools()->attach($request->id);
return redirect('school')->with('message', 'Successful update!');
}
Any help seeing what I'm missing is appreciated!
You have this in your User model
public function schools()
{
return $this->belongsToMany(School::class,'school_student','school_id', 'student_user_id');
}
and this in your Student model
public function schools()
{
return $this->belongsToMany(School::class);
}
not tested but imo you should specify the keys for the relation as you do in your user model.
EDIT : Or maybe
public function store(\App\Http\Requests\StudentAddSchoolStoreRequest $request)
{
$student = new Student();
// Replace id with user_id
$student->user_id = auth()->user()->id;
$school = new School();
$school->id = $request->id;
$student->schools()->attach($request->id);
return redirect('school')->with('message', 'Successful update!');
}
Please or to participate in this conversation.