JSON and Laravel Eloquent With Example
JSON and Laravel Eloquent With Example
ELOQUENT
DECODEWEB.IN
TABLE OF CONTENTS
JSON_EXTRACT() in eloquent
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.
JsonExample.php
public static function create($data)
{
$new = new self();
$new->name = $data['name'];
$new->json_details = $data['json_details''];
$new->save();
}
$dataToStore = [
'name' => $name,
'Json_details' => json_encode($details)
];
//saving data
JsonExample::create($dataToStore);
}
We can easily apply conditions on json data in laravel using -> (arrow notation), for example, fetch records where
salary is more than 50000.
JsonExample.php
JsonExample.php
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
Rather I have to explicitly tell eloquent to extract json field and then proceed.
select(DB::raw('sum(...)'))
Thank you :)