skip to Main Content

I try to POST data to database with "form-data" on "postman" with Laravel 9, and I try to return the data to JSON.

This is my controller:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppHttpRequests;
use AppM_Barang;

class Utama extends Controller
{
    public function index() {
        return view('Utama');
    }
    
    public function store(Request $request) {
        $this->validate($request, [
            'file' => 'required|max:2048'
        ]);
        $file = $request->file('file');
        $nama_file = time()."_".$file->getClientOriginalName();
        $tujuan_upload = 'data_file';
        if ($file->move($tujuan_upload,$nama_file)) {
            $data = M_Barang::create([
                'nama_produk' => $request->nama_produk,
                'harga' => $request->harga,
                'gambar' => $nama_file
            ]);
            $res['message'] = "succsess!";
            $res['values'] = $data;
            return response($res);
        }
    }
}

I get the following result:

enter image description here

This is my expected result:

enter image description here

2

Answers


  1. In Postman’s headers section, you have to set Accept and content-type to application/json:

    Image

    Login or Signup to reply.
  2. You need to send data from raw section in JSON Format, and try to send your image in base64 format (because its very convenient way to store a image into file system via the API).

    Example:{"profile_pic":"data:image/png;base64,iVBORw0KGgoAAAANSUh (base64 image string)"}

    you can convert base64 image here https://www.base64-image.de/
    and in Android and iOS has some libraries for converting image to base 64 while sending data to API

    Welcome in Advance.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search