Reputation: 341
I have received an array request from API endpoints and trying to save to the database but it's saving all an array request body to every column table.
Below is array posting to every column
s:284:"{"TransactionType":"Pay
Bill","TransID":"MBL51H83P1","TransTime":"20201603457857","TransAmount":"100","BusinessShortCode":"600000","BillRefNumber":"EDSJH90","InvoiceNumber":"1232","OrgAccountBalance":"500","MSISDN":"254710306000","FirstName":"D","MiddleName":"TANUI","LastName":"KIP"}";
Laravel function receiving the request
$data = json_decode($request->getContent() );
$mydata= serialize(json_encode($data));
$trn = new MpesaTransaction;
$trn->TransactionType = $mydata;
$trn->TransID = $mydata;
$trn->TransTime = $mydata;
$trn->TransAmount = $mydata;
$trn->BusinessShortCode = $mydata;
$trn->BillRefNumber = $mydata;
$trn->InvoiceNumber = $mydata;
$trn->OrgAccountBalance = $mydata;
$trn->MSISDN = $mydata;
$trn->FirstName = $mydata;
$trn->MiddleName = $mydata;
$trn->LastName = $mydata;
$trn->save();
Now how do I save each array value to its respective column?
Upvotes: 1
Views: 919
Reputation: 496
Your code is wrong. If $request->getContent() is json then you need decode to array. You can test with my code.
$data = json_decode($request->getContent(),true );
$trn = new MpesaTransaction;
$trn->TransactionType = $data['TransactionType'];
$trn->TransID = $data['TransID'];
$trn->TransTime = $data['TransTime'];
$trn->TransAmount = $data['TransAmount'];
$trn->BusinessShortCode = $data['BusinessShortCode'];
$trn->BillRefNumber = $data['BillRefNumber'];
$trn->InvoiceNumber = $data['InvoiceNumber'];
$trn->OrgAccountBalance = $data['OrgAccountBalance'];
$trn->MSISDN = $data['MSISDN'];
$trn->FirstName = $data['FirstName'];
$trn->MiddleName = $data['MiddleName'];
$trn->LastName = $data['LastName'];
$trn->save();
Upvotes: 0
Reputation: 24276
If you're sure that the response contains all the columns you have on your table, then you can simply use the create
method on the model:
$data = json_decode($request->getContent(), true);
MpesaTransaction::unguarded(static function() use ($data) {
MpesaTransaction::create($data);
});
Otherwise, you must set the parameters one by one:
$model = new MpesaTransaction;
$model->TransactionType = $data['TransactionType'];
// ........
$model->save();
Upvotes: 1