首页 > 解决方案 > Laravel 8 没有从包“\Conner\Tagging\Taggable;”中找到“标签”

问题描述

当我想从头开始创建一个新标签时,该代码可以完美运行,但$skillsQuery->count() > 0在 if 语句中输入时。它打印...

方法 Illuminate\Database\Eloquent\Collection::tag 不存在。

如何使用此软件包更新标签?

控制器

<?php

public function storeSkills(Request $request)
{
    $id = auth()->user()->id;
    $skillsQuery = Skill::where('created_by', $id)->get();

    // If skill exists
    if ($skillsQuery->count() > 0) {
        $input = $request->all();
        $tags = explode(", ", $input['name']);
        // $skill = Skill::create($input);
        $skillsQuery->tag($tags);
        $skillsQuery->created_by = $id;

        if ($skillsQuery->save()) {
            return redirect()->route('profile')->with('success', 'Skills updated successfully');
        } else {
            return redirect()->route('profile')->with('error', 'Error updated your Skills!');
        }
    } else {
        $input = $request->all();
        $tags = explode(", ", $input['name']);
        $skill = Skill::create($input);
        $skill->tag($tags);
        $skill->created_by = $id;

        if ($skill->save())
            return redirect()->route('profile')->with('success', 'Skills stored successfully');
        else {
            return redirect()->route('profile')->with('error', 'Error storing your Skills!');
        }
    }
}

标签: phplaraveltagslaravel-8

解决方案


调用->get()a的结果Illuminate\Database\Query是您将收到一个Illuminate\Database\Collection不包含->tag()方法的 a 实例。即使它是一个查询(通过删除->get()),这仍然不起作用,因为您不能从集合中调用关系方法。

相反,如果您循环,skillsQuery那么您将收到一个Model对象的实例,然后您可以访问它的函数和/或关系:

$skillsQuery->each(function ($skill) use ($tags) {
  $skill->tag($tags); // or perhaps ->retag($tags); here
});

推荐阅读