Laravel JSON Data Search/Filter From Database Example

  • 24-07-2022
  • 1436
  • Laravel 9
  • Haresh Chauhan

Laravel JSON data search from the database; laravel JSON data filter using where clauses. In this post, I will teach you how to find or filter data that you store in the database in JSON format in the table column. Laravel provides a method to easy way to find or search data from the database column.

The whereJsonContains() method will help us to filter and find JSON data from the database table column. At the end of this post, you will say to filter and apply where caused in the laravel query to find JSON content.

To filter data based on JSON content and searchable based on it. i have add a post column inside the users table.

Now I want to find user who has red color, So using laravel JSON where method i will find inside the post->color column object. follow the below given example.

JSON DATA EXAMPLE :
{
    "color":"red",
    "value":"#f00"
},
{
    "color":"green",
    "value":"#0f0"
},
{
    "color":"blue",
    "value":"#00f"
}

Attributes Set In Laravel Model

JSON Data Database Preview :
image

You can see I have stored JSON objects inside the post column in the database.

Example OF Filter :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class HomeController extends Controller
{
    public function index(Request $request)
    {
        $user = User::query();
    
        if($request->has('color')) {

            $user = $user->whereJsonContains('post->color', $request->color);
        }
        
        $user = $user->get();

        dd($user);
    }
}

whereJsonContains method provides easy why find or filter JSON store data in the database.


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :