Laravel标签CRUD

时间:2016-12-28 05:48:26

标签: php laravel laravel-5 laravel-5.3

我已经在网上阅读或观看了许多laravel教程,大部分教程都是'标记系统有一个功能:

标签CRUD有自己的路由器,首先,在创建新帖子时添加新标签和选择标签。但是如果我想在创建像wordpress这样的帖子时动态添加标签或更新标签,我该怎么办? (我使用bootstrap-tagsinput插件)

例如:

标记路由器

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

标签CRUD都以这种方式工作。

我想做的是:

发布路由器

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

当我创建新帖子或编辑帖子时,我也可以在不使用标记路由器的情况下添加或删除标签

对于创建帖子,我可以使用laravel的saveMany方法,如下所示:

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

但是当我编辑帖子时,我也想删除标签或添加新标签,我该怎么办呢?

3 个答案:

答案 0 :(得分:0)

使用this tagging package具有您想要的所有功能,因此您不必重新发明轮子。

因此,您可以在其中取消标记或删除标记或完全重新标记

$post->untag('Cooking'); // remove Cooking tag
$post->untag(); // remove all tags
$post->retag(array('Fruit', 'Fish'));

答案 1 :(得分:0)

您可以轻松使用:

bundle identifier

您可以查看“同步关联”部分下的功能$post->tags()->sync($request->tags, false); documentation 你可以看到this answer

答案 2 :(得分:0)

为时已晚。但我有同样的问题,谷歌搜索。 我在这里找到了一篇不错的文章:https://www.amitmerchant.com/attach-detach-sync-laravel/

就我而言:

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));
    }

希望它可以帮助某人。