Home > Software engineering >  How to Post with request to create new data from form using guzzle - Laravel
How to Post with request to create new data from form using guzzle - Laravel

Time:08-06

I have this function in my controller:

public function store(Request $request)
{
    $client = new Client();
    $headers = [
        'Authorization' => $token,
        'Content-Type' => 'application/json'
    ];
    $body = '{
    "DocNo": 1167722,
    "AOQty": 0,
    "TL": [
        {
        "Key": 11678,
        "Code": "Screw Hex",
        "Detail": true,
        "DTL": []
        }
    ]
    }';
    $request = new Psr7Request('POST', 'http://example.com/api/Order/', $headers, $body);
    $res = $client->sendAsync($request)->wait();
    echo $res->getBody();

}

that will store the data to the external API

but i want to POST the data from a form

when i work with normal routing (not API) i usually do this:

'Key' => $request->Key,

how can i achieve the above with guzzle?

currently when i submit the form from the view it will submit the above function (store) as static data, how can i submit the data from the form?

UPDATE:

When i use Http as showing below:

$store = Http::withHeaders([
        'Content-Type' => 'application/json',
        'Authorization' => $token,
    ])->post('http://example.com/api/Order/', [
        'DocNo' => "SO-000284",
        'AOQty' => 0.0,
        'TL[Key]' => 11678,
        'TL[Code]' => "SCREW HEX CAPHEAD 6X30MM",
        'TL[Detail]' => true,
        'TL[DTL]' => [],
    ]);
            echo $store;

it will store everything before [TL] Array, it won't store anything of:

        'TL[Key]' => 11678,
        'TL[Code]' => "SCREW HEX CAPHEAD 6X30MM",
        'TL[Detail]' => true,
        'TL[DTL]' => [],

am i doing it wrong?

CodePudding user response:

You can use HTTP client provided by Laravel.

$response = Http::withToken($token)->post('http://example.com/users', $request->only(['request_param_1', 'request_param_2']));

Or

$data = [];
$data['param_1'] = $request->get('param_1');
$data['param_2'] = $request->get('param_2');
$data['param_3'] = $request->get('param_3');
$response = Http::withToken($token)->post('http://example.com/users', $data);

Edit

$data = [
    'DocNo' => "SO-000284",
    'AOQty' => 0.0,
    'TL' => [
        'key' => 11678,
        'Code' => "SCREW HEX CAPHEAD 6X30MM",
        'Detail' => true,
        'DTL' => [],
    ]
];

CodePudding user response:

SOLUTION:

Using Http client:

'TL' => array ([
    'Dtl' => "",
    'Code' => "Screw Hex",
    'IsDetail' => true,
    "DTL" => [],
    ])
    ]);
  • Related