Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Getting a JSON element from a DB in Eloquent
Graham Morby
Graham Morby

Posted on

     

Getting a JSON element from a DB in Eloquent

So I had an issue come up today that required me to pull some data out of a DB for a report. That included some data that was stored in a JSON object.

So we have a column called params and in that we have a JSON Object that looks like so

{"1":"one","2":"two","3":"three","4":"four"}
Enter fullscreen modeExit fullscreen mode

So in my report, I need to access number 3, and how we do that is by using json_extract(), like so

$results=DB::table('testing')->select(DB::raw('json_extract(params, "$.4") as number'))->get();
Enter fullscreen modeExit fullscreen mode

So in the json_extract the first param it expects is the column name and following that is the field. You can then add more items to the select statement using a comma and we can write a full query like so

$results=DB::table('testing')->select('id',DB::raw('json_extract(params, "$.4") as number'),'type''created_at')->get();
Enter fullscreen modeExit fullscreen mode

And that will pull the data we need and all is great!

Enjoy folks and as always any updates or code reviews on this post please leave a comment down below

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
sashaajin profile image
Sasha Ajintarev
I am FullStack web developer
  • Education
    Plovdiv
  • Work
    Shkolo
  • Joined

how to move extracted value from char to integer

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Hey guys, 15-year developer! I code with Vue.js and Python, I love to learn but also love to teach! So I try and write informative tutorials and posts. I am new to blogging and would love any feedback
  • Location
    Portsmouth UK
  • Work
    Senior Developer Leighton
  • Joined

More fromGraham Morby

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp