You have the $book instance, so you need to attach the $student_id throught the students relation with the extra pivot data:
$student_id = 1;
$book->students()->attach ([
$student_id => ['author_id' => $author_id]
]);
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello Folks, In my project I'm trying to use attach method somehow getting a weird error. i.e.
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "author_id" violates not-null constraint DETAIL: Failing row contains (41, 1, null). (SQL: insert into "book_student" ("book_id", "student_id") values (41, 1), (41, 1), (41, 1))
Here are my logic and relationship
Book.php (Model)
public function students()
{
return $this->belongsToMany(Student::class, 'book_student')->withPivot('author_id');
}
Logic
$book = Book::find($id);
$author_id = 1;
$student_id = 1;
$book->students()->attach ([
$book->id,
$student_id,
$author_id
]);
Am I doing wrong here? Confused I don't know why I'm getting that error back. Any help that would be great.Thanks in advance
Yes, and the code I gave you will achieve just that. You are using a Book instance's students relationship to attach a specific $student_id along with the extra author_id pivot data
Please or to participate in this conversation.