【问题标题】:Laravel tags CRUDLaravel 标记 CRUD
【发布时间】:2017-05-12 09:13:36
【问题描述】:

我在网上阅读或观看过很多 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);

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

【问题讨论】:

    标签: php laravel laravel-5 laravel-5.3


    【解决方案1】:

    为时已晚。但我有同样的问题,谷歌搜索这个。 我在这里找到了一篇好文章: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));
        }
    

    希望它对某人有所帮助。

    【讨论】:

      【解决方案2】:

      您可以轻松使用:

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

      您可以在同步关联部分查看函数 sync documentation 你可以看到this answer

      【讨论】:

        【解决方案3】:

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-12-25
          • 1970-01-01
          • 2018-06-23
          • 2023-03-20
          • 1970-01-01
          • 2022-09-30
          • 1970-01-01
          相关资源
          最近更新 更多