Sling Academy
Home/PHP/How to update JSON column in Laravel Query Builder

How to update JSON column in Laravel Query Builder

Last updated: January 17, 2024

Introduction

In recent versions of Laravel, working with JSON columns has never been easier, thanks to the robust features of Eloquent and the Query Builder. In this tutorial, we will explore several methods on how to update a JSON column efficiently using Laravel’s Query Builder.

Before diving into code examples, ensure you are using a database that supports JSON column types such as MySQL 5.7+, PostgreSQL 9.4+, or SQL Server 2016+.

Prerequisites

  • Laravel 8.x or newer
  • Database connection with JSON column support
  • Knowledge of Laravel’s Query Builder

Understanding JSON Column Types

JSON columns allow us to store data in a structured, schema-less format, right within a SQL database. In the context of Laravel, these can be manipulated just like other field types.

Updating a JSON Column

To begin, we’ll assume you have a users table with a JSON column named options. We’ll demonstrate various snippets on how to update this JSON column.

Basic Update

// Using the query builder
db-
->table('users')
->where('id', 1)
->update(['options->language' => 'en']);

This snippet updates the language key of the JSON column options for the user with ID 1.

Incrementing a Value

// Incrementing a value in a JSON column
db-
->table('users')
->where('id', 1)
->update(['options->logins_count' => DB::raw('(options->">$.logins_count") + 1')]);

This code will increment the logins_count value by 1 for the specified user.

Updating Multiple Values

// Updating multiple values
db-
->table('users')
->where('id', 1)
->update([
    'options->language' => 'fr',
    'options->timezone' => 'Europe/Paris'
]);

This will update both the language and the timezone keys within the JSON column.

Using Raw Expressions

// Using raw expressions to modify JSON
db-
->table('users')
->where('id', 1)
->update([
    'options' => DB::raw('json_set(options, "$.notifications.email", true)')
]);

This raw expression utilizes the json_set MySQL function directly to update the nested email notification setting.

Handling JSON Arrays

// Appending to a JSON array
db-
->table('users')
->where('id', 1)
->update([
    'options' => DB::raw('json_array_append(options, "$.favorite_colors", "blue")')
]);

In this snippet, we append a new element to a JSON array named favorite_colors.

Best Practices and Considerations

When updating JSON columns, you should keep several best practices in mind:

  • Do not store large amounts of data in a JSON column, as it can affect performance.
  • Always validate and sanitize incoming JSON data to prevent issues such as SQL injection or data corruption.
  • Consider the implications on indexing and searchability when storing data in JSON format.

Conclusion

In this tutorial, we’ve covered the basics of updating JSON columns using the Laravel Query Builder. From simple updates to manipulating arrays, you should now have a strong foundation for handling JSON data in your Laravel applications. Remember to refer to Laravel’s documentation for the most up-to-date features and functions available to work with JSON columns.

Next Article: Increment and Decrement of Column Values in Laravel Query Builder

Previous Article: Laravel Query Builder: Insert and Get ID of Last Inserted Row

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array