Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nitz25's avatar

How to save JSON data to database?

Hello, I have some difficulties on how can I save my json data to database, can someone help me about this?

In my controller I have this code for saving ..

    $banks = $data['banks'];  //this is my json data
        $banks_data = (array) json_decode($banks); //converted as array
      
//inside my json file I have data for bank_code and bank_name

        $payment_types = PaymentBank::create([
        'bank_code' => Str::upper(trim($banks_data['bank_code'])),
                'bank_name' => Str::upper(trim($banks_data['bank_name'])),
        'auid' => Auth::user()->id,   
        ]);

Any help will be appreciated. Thanks

0 likes
5 replies
tykus's avatar

The code you have shared would appear to work providing your JSON is well-formed. I would dump the $data['banks'] variable to ensure you are getting the JSON you expected. Otherwise, give us some further details about errors/failures.

As an aside, you can get an array back from json_decode($banks, true) - the second argument true will give you an associative array.

1 like
nitz25's avatar
nitz25
OP
Best Answer
Level 2

@tykus_ikus thanks for the idea I used the $banks_data = json_decode($banks, true); then I loop the banks to get all the data


foreach($banks_data as $bank) { 
            $payment_bank = PaymentBank::create([
                'bank_code' => Str::upper(trim($bank['bank_code'])),
                'bank_name' => Str::upper(trim($bank['bank_name'])),
            ]);
        }

forri's avatar

use migrage factory

$factory->define(Payment::class, function (Faker\Generator $faker) {
  $subjectInrto = [
    'class_id'=>2,
    'start_at'=>'2016年1月13日',
    'end_at'=>'2016年2月13日',
    'remark'=>'xxxxxx',
  ];

  return [
    'subject_intro' => json_encode($subjectInrto),
  ];
});
1 like

Please or to participate in this conversation.