Codementor Events

json_extract() and laravel eloquent with example

Published Jan 21, 2020
json_extract() and laravel eloquent with example

JSON is short form of JavaScript Object Notation, which is used to store data and since it is very lightweight hence majorly used for transporting data to and from a web server. In earlier days, XML was used for this very purpose but writing and reading XML data was very tedious while JSON on the other hand, is self describing.

In today’s topic I am going to show you how to store JSON data into MySQL and access those data using laravel eloquent query builders.

Storing JSON data in MySQL using Laravel

First let’s create a dummy table using migration command.

Schema::create(json_examples, function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->text('json_details'); //using text datatype to store json
            $table->timestamps();
        });

As you can see I used text datatype for storing js object.

Next, let’s create a corresponding Model for the same

| php artisan make:model JsonExample |

Example Model

public static function create($data)
{
    $new = new self();
    $new->name = $data['name'];
    $new->json_details = $data['json_details''];
    $new->save();
}

So in controller we can do something like this:

public function storeEmpData(Request $request)
{
    ...
    $name = $request->name';
    $details = ['emp_code' => '001', 'date_of_joining' => Carbon::parse($request->doj), 'salary' => '50000'];
   
    $dataToStore = [
        'name' => $name,
        'Json_details' => json_encode($details)
      ];

      //saving data
      JsonExample::create($dataToStore);
}

Processing Json data in Laravel eloquent.

In where()

We can easily apply conditions on json data in laravel using -> (arrow notation), for example, fetch records where salary is more than 50000.

Example Model

public static function getSalaryMoreThan($salary)
{
    return self::where('json_details->salary','>',$salary)->get();
}

Another example, we need records of employees who joined the company before a date for instance 9th November 2018.

Example Model

public static function getEmployeesBeforeDate($date)
{
    return self::whereDate("json_extract('json_details', '$.doj')", '<', $date)->get()
}

As you can see above, I used json_extract() method which is MySQL’s function to extract a field from JSON column since I can not simply instruct eloquent using arrow operator like

| return self::whereDate('json_details->doj', '<', $date)->get() |

Rather I have to explicitly tell eloquent to extract json field and then proceed.

JS object in DB::raw()

Many times we need to use MySQL’s aggregate functions like SUM() as per the requirement, in that case we use DB facade. For example,

| select(DB::raw('sum(...)')) |

How to access json field in MySQL’s aggregate function ?

It is very simple, let’s take an example, we need to sum total salary of employees.

public static function findTotalSalary()
{
    return self::select(DB:raw('sum("json_extract('json_details', '$.salary')") as total_salary'))->get();
}

Conclusion

That’s all about this topic friends, I hope you learned something new which you haven’t thought about. I thought I should share this knowledge as I encountered such problem while working on a project today where I do save additional data in json format. Do comment your reviews and experiences below.

Thank you 🙂

Ebooks available now

You can download this article’s PDF eBooks for offline reading from below:

Dinesh Suthar is a full time web developer. He loves to code in Laravel, Codeigniter and learning NodeJS. He is passionate about blogging, sharing his knowledge of web development and programming to the world through his blog.

Discover and read more posts from Decode Web
get started
post commentsBe the first to share your opinion
Show more replies