@Melodia check network tab to know what exact error do you get https://d.pr/v/rbfJuQ
Jun 26, 2018
3
Level 5
How to update record if no image is added | VueJs
For the update of my post table I want to add a validation to check if an image was uploaded. If no image is uploaded, everything is uploaded except the image, else it means there is an image and that is update.
I tried this in my Controller:
public function update(Request $request, $id)
{
if(request('photo')){
$exploded = explode(',', request('photo'));
$decoded = base64_decode($exploded[1]);
if(str_contains($exploded[0], 'jpeg'))
$extension = 'jpg';
else
$extension = 'png';
$fileName = str_random().'.'.$extension;
$path = public_path().'/'.$fileName;
file_put_contents($path, $decoded);
$post = Post::findOrFail($id);
$post->title = request('title');
$post->description = request('description');
$post->category_id = request('category_id');
$post->user_id = Auth::id();
$post->photo = $fileName;
$post->save();
}
else{
$post = Post::findOrFail($id);
$post->title = request('title');
$post->description = request('description');
$post->category_id = request('category_id');
$post->user_id = Auth::id();
$post->save();
}
return response()->json([
'post' => $post,
], 200);
}
In my vue file I have the following:
editPost(){
if(this.update_post.photo == ''){
axios.put('/api/posts/' + this.update_post.id, {
title: this.update_post.title,
description: this.update_post.description,
category_id: this.update_post.category_id
})
.then(response => {
alert('updated');
this.showPosts();
})
.catch(function(error){
console.log(error);
});
}
else{
axios.put('/api/posts/' + this.update_post.id, {
title: this.update_post.title,
description: this.update_post.description,
category_id: this.update_post.category_id,
photo: this.update_post.photo
})
.then(response => {
alert('updated');
this.showPosts();
})
.catch(function(error){
console.log(error);
});
}
}
When I try to update a post, if no image is inserted I get 500 Internal server error:
app.js:14233 PUT http://sidneyblog.local/api/posts/52 500 (Internal Server Error)
How can I fix that?
Please or to participate in this conversation.