I am trying to create a new record in during transaction by creating the model instance and then decorate all properties.
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function authors()
{
return $this->belongsToMany(
User::class, 'blog_post_authors', 'post_id', 'author_id'
);
}
// 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, ?))
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();