R
R
RobQwerty2022-02-02 18:33:44
Laravel
RobQwerty, 2022-02-02 18:33:44

How to edit JSON?

I have a User field inside which there is a column balance (type TEXT ) , which should store json data by type

{"BTC": {
    "Bitcoin_wallet": "NULL",
    "Bitcoin_balance": "0.00"
  },
"ETH": {
    "Ether_wallet": "NULL",
    "Ether_balance": "0.00"
  }
}

in the Users model: protected $casts = ['balance' => 'object'] is.
By calling dd($user->balance->BTC); clearly shows the value :

61faa3886e06d604725110.png

But when you try to edit, for example Ether_wallet, and save the new value - it erases all data from the column and replaces the old data with {"NULL":"input data here"}.

I'm trying to save data like this:
$in['balance']=$user->balance;
$in['balance'] = [
              $user->balance->BTC->Bitcoin_wallet => $request->Bitcoin_wallet,
              $user->balance->ETH->Ether_wallet => $request->Ether_wallet
]

What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2022-02-02
@delphinpro

1. It is better to use not TEXT but JSON
2. There is a mention of this in the documentation. To set nested values:
2.1 use arrow notation

$casts = [
  'balance' => 'array',
];

$user->balance['BTS->Bitcoin_wallet'] = '';

2.2 You can use a special cast for this
$casts = [
  'balance' => AsArrayObject::class,
];

$user->balance['BTS']['Bitcoin_wallet'] = '';

If I didn't mess up anything. Check out the documentation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question