php - 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, ?))

Answer

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(); 

Answer

Solution:

You are creating a $postModel in terms that it is created in php, but it is not saved to the database yet, and therefore does not yet have an id since the id it's probably an auto-incrementing value determined by the database.

So first save your postModel, than apply the author relation.

Either do: $postModel = Post::create([...]); or add: $postModel->save();

Source