user4655002
user4655002

Reputation:

Update json column's individual values

So I have a user structure like so:

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('username');
        $table->text('phone');
        $table->string('address');
        $table->string('city');
        $table->string('state');
        $table->string('country');
        $table->string('postal');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('google2fa_secret');
        $table->text('balance');
        $table->rememberToken();
        $table->timestamps();
    });

Now, I am storing values in the 'balance' column like so

{
    "usd": 10,
    "gbp": 10,
    "eur": 10
}

How can I edit for example usd value but keep the others in the array with attributes?

How I am getting the attributes:

/**
 * Get the user's balance
 *
 * @return decimal
 */
public function getBalanceAttribute()
{
    return json_decode( $this->attributes['balance'] );
}

Upvotes: 0

Views: 573

Answers (1)

Nitish Kumar
Nitish Kumar

Reputation: 6276

Suppose in your users you want to fetch by id and then update then you can do something like this:

DB::table('users')
        ->where('id', 1)
        ->update(['balance->usd' => 12]);

But make sure that is an json column I mean you need to define $table->json('balance'); in your migration. Then you won't be requiring accessor to get json_encode attribute.

For more information check documentation part.

Upvotes: 1

Related Questions