Maximi
Maximi

Reputation: 569

Laravel sync/attach tags

I am working on tag functionality on Laravel and continue by this great tutorial: https://laracasts.com/series/laravel-5-fundamentals/episodes/22?autoplay=true

But i have problem with sync/attach functionality. When i try attach is it only updated post_tag table, not the tag table. Then all post is pointed to non existing tag with id 0.

Saving seems like:

...
if ($request->get('tags')) {
    $tagsarr = array_slice(array_unique($request->get('tags')), 0, (int)siteSettings('tagsLimit'));
    $post->tags()->attach($tagsarr);
}
    $post->save();

    return $post;

When I dd($tagsarr); i have:

array:3 [▼
  0 => "tag1"
  1 => "tag2"
  2 => "tag3"
]

After helping i change code to this:

...
$post->save();

    if ($request->get('tags')) {
        $tagsarr = array_slice(array_unique($request->get('tags')), 0, (int)siteSettings('tagsLimit'));
        $tagIds[] = Tag::firstOrCreate($tagsarr)->id;

        $post->tags()->attach($tagIds);
    }

    return $post;

The solution:

$post->save();

    if ($request->get('tags')) {
        $tagsarr = array_slice(array_unique($request->get('tags')), 0, (int)siteSettings('tagsLimit'));

        foreach($tagsarr as $tagitem) {
            $tagIds[] = Tag::firstOrCreate(['tag' => $tagitem])->id;
        }

        $post->tags()->attach($tagIds);
    }

    return $post;

Upvotes: 3

Views: 1685

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163798

attach() shouldn't do anything with tags table. If you're creating new post you should save object first:

$post->save();

And only then use attach().

Also, $tagsarr should contain IDs of tags, but not tag names.

Upvotes: 2

Related Questions