问题
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