How To Update MySQL JSON Column in Laravel

Hello Artisan

In this tutorial i will share with you that how we can update json column in laravel 8. Sometime we need to create json column in our database in scheme for our laravel application to reduce column or sometime table also.

In this Laravel json column example you will learn how we can update a specific json value from mysql json column in Laravel application. If you don't know then follow the tutorial from scratch.

Look this is our table and meta is our json column. 

public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->json('meta');
            $table->timestamps();
        });
    }

 

From this table you could imagine one contact (output to JSON for blog-post-readability) might look like this:

{
    "id": 1,
    "name": "Alphonse",
    "meta": {
        "wants_newsletter": true,
        "favorite_color": "red"
    }
}

 

Now we want to fetch specific value from json mysql column. So see the below query

$redLovers = DB::table('contacts')
    ->where('meta->favorite_color', 'red')
    ->get();

 

And you can use below code to update specific json value in Laravel. Let,s see

DB::table('contacts')
    ->where('id', 1)
    ->update(['meta->wants_newsletter' => false]);

 

Recommended : Avoid Pivot Table and Use Json Column in Laravel

 

Hope it can help you.