0

I have read or watched many laravel tutorials on the web,most of the tutorials' tagging system have a feature:

The tag CRUD has their own router,first,add new tags and select tags when create new post.But if I want to dynamically add tags or update tags when create post like wordpress, How can I do ? (I'm using bootstrap-tagsinput plugin)

For example:

Tag Router

Route::resource('tags','TagsController');

Tags CRUD all work in this way.

What I want to do is :

Post Router

Route::resource('posts','PostController');

When I create new post or edit post, I also can add or delete tags without use the Tag Router

For create post I can use laravel's saveMany method like this:

    $post = new Post();
    $post->someProperty = $someProperty;
    $post->save();
    $tags = [];
    foreach ($request->tags as $tag) {
        $tags[] = new Tag(['name' => $tag]);
    }
    $post->saveMany($tags);

But when I edit a post, I also want to delete tags or add new tags,How can I do for it?

3 Answers 3

0

use this tagging package which has all the features you want so you don't have to re-invent the wheel.

So, there you can untag or delete tag or retag completely

$post->untag('Cooking'); // remove Cooking tag
$post->untag(); // remove all tags
$post->retag(array('Fruit', 'Fish'));
Sign up to request clarification or add additional context in comments.

Comments

0

you can easily use:

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

you can review the function sync documentation under Syncing Associations section and you can see this answer

Comments

0

It's too late. But I have same issue and google search for this. I found a good article here: https://www.amitmerchant.com/attach-detach-sync-laravel/

in my case:

public function update(PostEditRequest $request)
    {
        $post = DB::transaction(function() use($request) {
            $post = Post::find($request->id);
            if (!$post) return $this->response404('Post is not found!!!');

            $data = $request->only(['title', 'content']);
            $post->update($data);

            $tags = collect($request->tags); // My tags are [{id: 1, name: 'PHP'}] I got from ajax request
            $post->tags()->sync($tags->pluck('id')); // <- This to add and also remove tag for the post 

            return $post;
        });
        return $this->successResponseWithResource(new PostResource($post));
    }

Hope it help someone.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.