Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

deepu07's avatar
Level 11

Attach method (Saving id's in Pivot table)

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

0 likes
9 replies
tykus's avatar

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]
]);
deepu07's avatar
Level 11

@tykus My pivot table has 3 columns i.e. book_id, student_id author_id. I want to add three ids to the pivot table.

tykus's avatar
tykus
Best Answer
Level 104

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

deepu07's avatar
Level 11

@tykus quick question... also the same trick works for updateExistingPivot() method?

tykus's avatar

Only for an individual instance of a related Model AFAIK

deepu07's avatar
Level 11

@tykus So If I Want to update existed pivot table record which one you will suggest writing an attach()or updateExistingPivot()?

deepu07's avatar
Level 11
$book->students()->updateExistingPivot (
            $student_id,
            ['author_id' => $request['author_id']]
        );

this will do the trick. Thanks again.

tykus's avatar

For an individual existing association:

$book->students()->updateExistingPivot($student, ['author_id' => $updatedAuthorId]); 

Please or to participate in this conversation.