Melodia's avatar

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?

0 likes
3 replies
Melodia's avatar

I see things like this in the preview tab:

{message: "Undefined offset: 1", exception: "ErrorException",…} exception : "ErrorException" file : "C:\xampp\htdocs\sidneyblog\app\Http\Controllers\AdminPostsController.php" line : 66 message : "Undefined offset: 1" trace : [{file: "C:\xampp\htdocs\sidneyblog\app\Http\Controllers\AdminPostsController.php", line: 66,…},…] 0 : {file: "C:\xampp\htdocs\sidneyblog\app\Http\Controllers\AdminPostsController.php", line: 66,…} class : "Illuminate\Foundation\Bootstrap\HandleExceptions" file : "C:\xampp\htdocs\sidneyblog\app\Http\Controllers\AdminPostsController.php" function : "handleError" line : 66 type : "->" 1 : {function: "update", class: "App\Http\Controllers\AdminPostsController", type: "->"} class : "App\Http\Controllers\AdminPostsController" function : "update" type : "->" 2 : {file: "C:\xampp\htdocs\sidneyblog\vendor\laravel\framework\src\Illuminate\Routing\Controller.php",…} file : "C:\xampp\htdocs\sidneyblog\vendor\laravel\framework\src\Illuminate\Routing\Controller.php" function : "call_user_func_array" line : 54

In the response tab I see this errors:

{
"message": "Undefined offset: 1",
"exception": "ErrorException",
"file": "C:\xampp\htdocs\sidneyblog\app\Http\Controllers\AdminPostsController.php",
"line": 66,
"trace": [
    {
        "file": "C:\xampp\htdocs\sidneyblog\app\Http\Controllers\AdminPostsController.php",
        "line": 66,
        "function": "handleError",
        "class": "Illuminate\Foundation\Bootstrap\HandleExceptions",
        "type": "->"
    },
    {
        "function": "update",
        "class": "App\Http\Controllers\AdminPostsController",
        "type": "->"
    },
    {
        "file": "C:\xampp\htdocs\sidneyblog\vendor\laravel\framework\src\Illuminate\Routing\Controller.php",
        "line": 54,
        "function": "call_user_func_array"
    },
cometads's avatar
...
        $exploded = explode(',', request('photo'));
        $decoded = base64_decode($exploded[1]);
        if(str_contains($exploded[0], 'jpeg'))
            $extension = 'jpg';
        else
            $extension = 'png';  
...

It looks like you're using a comma (',') as your explode() delimiter when you should be using a period ('.'). So $exploded[1] is undefined. Could also be request('photo') is not a string (it usually returns a Illuminate\Http\UploadedFile instance but it could be returning a string via magic method).

Regardless, the explode() call is incorrect to separate a file extension from the rest of the file name.

It's also worth noting that Laravel can get the file extension and do a lot more with files in requests for you.

Please or to participate in this conversation.