Level 104
$post is not saved to the database, so has no ID
$post = Post::create($request->all());
$post->tags()->attach($request->tags);
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi everyone. I have 3 tables: tags, posts, post_tag. I am creating post and attaching tag like this:
$post = new Post();
if($post->create($request->all()))
{
foreach ($request->input('tags') as $tag)
$post->tags()->attach($tag->id);
}
But Laravel saying like this:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id' cannot be null
Can you tell me simplest way to fix it?
$post is not saved to the database, so has no ID
$post = Post::create($request->all());
$post->tags()->attach($request->tags);
Please or to participate in this conversation.