I want to store tags with question in my project, and the relation between question and tags is many to many polymorphic (poly because I have another tables and they have tags field too)
In my QuestionController()
, when I want to store a question and tags, I get this error:
Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::save() must be an instance of Illuminate\Database\Eloquent\Model, string given
When I use save
instead of saveMany()
gives this error:
"message": "Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::save() must be an instance of Illuminate\Database\Eloquent\Model, array given
I also used sync()
, but tags aren't stored in the database.
I tasted it with postman.
And the method
is this:
public function store(StoreQuestionRequest $request)
{
$validatedData = $request->all();
////Because there is no need storage images and question codes
$question = Question::create($validatedData); //store question
//store tags
$tag = new Tag();
$tags = explode(",", $request->tag);//separate tags
$tag['tag'] = $tags;
$question->tags()->saveMany($tags);
return response()->json([
'success'=>true,
'message'=> 'successfully',
'data'=>$question
]);
}
So if you need to know about relations
, these are my models:
Question
:
public function tags(){
return $this->morphToMany(Tag::class, 'taggable');
}
Tag
:
public function questions(){
return $this->morphedByMany(Question::class, 'taggable');
}
it solved :
public function store(StoreQuestionRequest $request)
{
$validatedData = $request->all();
////Because there is no need storage images and question codes
$question = Question::create($validatedData); //store question
//store tags
$tagNames = explode(",", $request->tag);//separate tags
$tagIds = [];
foreach($tagNames as $tagName)
{
$tag = Tag::firstOrCreate(['tag'=>$tagName]);
if($tag)
{
$tagIds[] = $tag->id;
}
}
$question->tags()->sync($tagIds);
return response()->json([
'success'=>true,
'message'=> 'successfully',
'data'=>$question
]);
}