trihead's avatar

Select JSON data from DB and Display

I have JSON string saved in my DB, is there any way to extract the information and use it?

[{"last_name": "Doe", "first_name": "John"}]

I stored this data in a JSON field with the name of meta

Thanks for your help

0 likes
6 replies
lanatel's avatar

You can have accessor in your model class

public function getMetaAttribute($value)
{
    return json_decode($value, true);
}

Than you can use it like a regular array

For example

$user = App\User::find(1);

$firstName = $user->meta['first_name'];
1 like
click's avatar

You can use the $casts attribute that automatically handles this for you see https://laravel.com/docs/5.6/eloquent-mutators#array-and-json-casting

class YourModel extends Model
{
    protected $casts = [
        'your_db_column_with_json' => 'array',
    ];
}

// usage: 
$yourModel->your_db_column_with_json = [1,2,3];
$yourModel->save(); // now the array is automatically stored as json string in your database

$array = $yourModel->your_db_column_with_json;
// will return the array [1,2,3]
1 like
trihead's avatar

@m-rk I already added this lines t my User.php (Model) file, but the rest I don't understand how to handle it.

    protected $casts = [
        'id' => 'int',
        'meta' => 'array'
    ];
trihead's avatar

@lanatel

Thanks, what is the deal with $value, where should I use it? I am not good at working on Arrays too :(

click's avatar

Forget about the whole json in your model. You just use array's from now on. The array is stored as json in your database but that is something you do not need to worry about.

It is in the documentation: https://laravel.com/docs/5.6/eloquent-mutators#array-and-json-casting

So if you want to store meta data on your model you just do:

$yourModel->meta = ['first_name' => 'John', 'last_name' = 'Doe']; 
$yourModel->save(); 

// and later on if you want to retrieve your meta data array
$yourModel->meta;

// or 
$yourModel->meta['first_name'] 
// and
$yourModle->meta['last_name'] 
1 like
lanatel's avatar

@trihead in this case $value is your json from db.

But m-rk's way is better and easier. Just try to work with arrays and you will see how easy it is.

Please or to participate in this conversation.