Laravel : how to create unique tag in tags model

我怕爱的太早我们不能终老 提交于 2021-01-29 07:08:54

问题


I want create tag for posts . I don't want tags repetitions to be saved,But it is stored repeated

public function store(Request $request)
{
    $data = $request->all();
    $post = Post::create($data);
    if ($post && $post instanceof Post) {
        $tags = $request->input('tags');
        foreach ($tags as $tag){
                $newTag = Tag::create(['name'=>$tag]);
                $tags[] = $newTag->id;
        }
            $post->tags()->sync($tags);
        return redirect()->back();
    }
}

How can it be done?


回答1:


updateOrCreate method will help check It will create data if it not exists and update in case it already in db

Tag::updateOrCreate(['name'=>$tag]);


来源:https://stackoverflow.com/questions/63661078/laravel-how-to-create-unique-tag-in-tags-model

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!