'Update NuxtJs checkbox returning array to string error
I have this in my nuxtjs file
<div class="mt-2">
<span class="block uppercase text-blueGray-600 text-xs font-bold mb-2">Categories</span>
<div v-for="(category, i) in categories" :key="i">
<label class="inline-flex items-center" v-if="category.id != null">
<input type="checkbox" class="form-checkbox" v-model="category.id"
:value="category.id"
>
<span class="ml-2" v-html="category.name"></span>
</label>
<label class="inline-flex items-center" v-else>
<input type="checkbox" class="form-checkbox" v-model="categories.id"
:value="categories.id"
>
<span class="ml-2" v-html="categories.name"></span>
</label>
</div>
</div>
and i have this in my controller
public function store(PostRequest $request)
{
$post = Post::create([
'title' => $request->title,
'body' => $request->body,
'excerpt' => $request->excerpt,
'user_id' => auth()->id(),
]);
$post->categories()->sync($request->catSelected);
return response()->json([
'post' => $post,
'message' => 'Post created successfully.'
], 200);
}
/**
* Display/Edit the specified post.
*
* @param \App\Models\Post $post
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$post = Post::find($id);
$cat = $post->categories()->get();
return response()->json([
'post' => $post,
'categories' => $cat
]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Post $post
* @return \Illuminate\Http\Response
*/
public function update(PostRequest $request, Post $post)
{
$post->update([
'title' => $request->title,
'body' => $request->body,
'excerpt' => $request->excerpt,
]);
$post->categories()->attach($request->categories);
return response()->json([
'post' => $post,
'message' => 'Post updated successfully.'
], 200);
}
Vuejs script
data:() =>({
errors: [],
title: '',
body: '',
excerpt: '',
categories: [],
}),
async fetch(){
await this.$axios.get('/api/post/'+this.$route.params.id)
.then(response => {
this.title = response.data.post.title
this.body = response.data.post.body
this.excerpt = response.data.post.excerpt
this.categories = response.data.categories
})
},
methods: {
async updatePost(){
this.errors = []
await this.$axios.put('/api/post/update/'+this.$route.params.id , {
title: this.title,
body: this.body,
excerpt: this.excerpt,
categories: this.categories
}).then(()=> this.$router.push('/posts'))
.catch(error => {
if(error.response.status !== 422) throw error
this.errors = Object.values(error.response.data.errors).flat()
})
},
The problem is that anytime i uncheck the selected box and i save it gives "message": "Array to string conversion", but the field is deleted from the database.
Another thing is that i want the category to still be present but unchecked just in case i want to check it again
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
