I am using select2 to select tags in my post but I would like to implement the tagging feature. I am able to save new tags but I am stuck linking the tag to the post on my pivot table.

SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'bike' for column 'tag_id' at row 1 (SQL: insert into post_tag (post_id, tag_id) values (167, bike))

$post = new Post;
$post->post_category_id = $request->post_category_id;
$post->title = $request->title;
$post->body = $request->body;
$post->meta_description = $request->meta_description;
$post->slug = $request->slug;
$post->user_id = auth()->id();

$tags = $request->input('tags');

foreach ($tags as $tag) {
    if (is_numeric($tag)) {
        $tagArr[] = $tag;
    } else {
        $newTag = Tag::create(['name' => $tag]);
        $newTag = $newTag->id;
    }
}

$post->save();
$post->featured()->sync($request->featured, false);
$post->tags()->sync($request->tags, false);

Session::flash('success', 'The blog post was saved successfully!');

return redirect()->route('posts.show', $post->id);

I know I can change the tag_id to a string but I wondered if there was another way around it.

0 Answers