Home > Database > Mysql Tutorial > How to Search for Emails Within a JSON Column in Laravel?

How to Search for Emails Within a JSON Column in Laravel?

Linda Hamilton
Release: 2024-10-29 07:13:02
Original
334 people have browsed it

How to Search for Emails Within a JSON Column in Laravel?

Eloquent Queries for Searching JSON Columns

In Laravel, searching JSON columns can be a challenge. This article will delve into a specific scenario involving a "To" column that stores email addresses in a JSON format.

The Problem

Given a "To" column with JSON data like this:

<code class="json">[
    {
        "emailAddress": {
            "name": "Test", 
            "address": "test@example.com"
        }
    }, 
    {
        "emailAddress": {
            "name": "Test 2", 
            "address": "test2@example.com"
        }
    }
]</code>
Copy after login

The goal is to retrieve emails sent to "test@example.com." Using whereJsonContains('to->emailAddress->address', 'test@example.com') returns no results.

The Solution

The issue lies in the use of the arrow operator (->). In JSON arrays, the arrow operator is not supported. Instead, the double square bracket notation ([['emailAddress' => ['address' => 'test@example.com']]]) should be used.

The corrected query is:

<code class="php">DB::table('emails')
   ->whereJsonContains('to', [['emailAddress' => ['address' => 'test@example.com']]])
   ->get()</code>
Copy after login

This query will return all emails that include "test@example.com" in the "To" column.

The above is the detailed content of How to Search for Emails Within a JSON Column in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template