So, I want to insert an entire array of values into a particular column and I don’t know exactly what to do. Everything I have tried gives me the "Array to string conversion" error.
Here is my controller code:
public function processInternationaTransfer(Request $request)
{
$international_info = Validator::make($request->all(),
[
'beneficiary_name' => 'required',
'beneficiary_acc_num' => 'required|numeric',
'beneficiary_bank' => 'required',
'beneficiary_swiftcode' => 'required',
'routing_transit_no' => 'required|numeric',
'currency' => 'required',
'amount' => 'required|numeric',
'note' => 'required',
]
);
if($international_info->fails())
{
return response()->json(['errors'=>$international_info->errors()->all()]);
}
$info = $international_info->validated();
$balance = $info['currency'].'_balance';
if(user_details()->$balance < InternationalAmount($info['amount']))
{
return response()->json(['insufficient_amount'=>'Insufficient Amount']);
}
else
{
TransactionLog::create([
'username' => user()->username,
'type' => 'Exchange',
'cred_deb' => 'Debit',
'time'=> Carbon::now('Africa/Lagos')->format('l, d F, Y g:i A'),
'status' => 2,
'amount'=>InternationalAmount($info['amount']),
'currency'=>$info['currency'],
'reason' => $info['note'],
'inter_details' => $info,
'transaction_id' => rand(100000000, 999999999),
]);
return response()->json(['success'=>'Transaction Processed, Awaiting Confirmation']);
}
}
How do I insert that array of values into the inter_details column?
I tried inserting it as it is above, and it gives me "array to string conversion" error.
I want to be able to fetch it after inserting it.
2
Answers
To insert an array of values into a particular column, you need to use the DB facade’s insert method. The insert method takes an array of values as its first argument and the table name as its second argument.
For example, if you want to insert an array of values into the inter_details column, you can do the following:
The json_encode() function is used to convert the array into a JSON string, which can then be stored in the database.
To fetch the array of values from the database, you can use the DB facade’s select method. For example:
The json_decode() function is used to convert the JSON string back into an array. The second argument of the function is set to true, which tells the function to return an associative array instead of an object.
Now you have the array of values stored in the $inter_details variable, which you can use as you wish.
First of all you need to make sure that the
inter_details
can accept many characters the best way to do that is to use thejson()
in migrationsthen add a casts to the
TransactionLogs
Modelin this way you can access the inter_details as an array when you fetch it from the database you don’t need to use
json_encode()
andjson_decode()
. if you want tocasts
it in other types there are many more from the documentationEloquent: Mutators & Casting – Attribute Casting