Search code examples
phplaraveleloquenttransactions

Laravel error on save pivot table in transaction mode


I am trying to create a new record in during transaction by creating the model instance and then decorate all properties.

Post model

/**
 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
 */
public function authors()
{
    return $this->belongsToMany(
       User::class, 'blog_post_authors', 'post_id', 'author_id'
    );
}

Saving model

// start transaction mode
DB::beginTransaction();

$postModel = new Post(
    ['title' => 'Hello world!']
);

// relate authors
$postModel->authors()->attach(7);

\DB::commit();

However, its throwing an exception even before transaction being committed.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id' cannot be null (SQL: insert into `blog_post_authors` (`author_id`, `post_id`) values (7, ?))

Solution

  • you should save the Post Model , maybe you missed that:

    DB::beginTransaction();
    
    $postModel = new Post(
        ['title' => 'Hello world!']
    );
    $postModel->save();
    
    // relate authors
    $postModel->authors()->attach(7);
    
    \DB::commit();