Debarshi Das
Debarshi Das

Reputation: 49

How to retrieve object value from database stored as json

I have stored data in json format

        $data = [
            'applicant_name' => auth()->user()->name,
            'post_held' => getDesignation(auth()->user()->designation_id)->name,
            'department' => request('department')
        ];

        $leave = new Leave;

        $leave->user_id = auth()->user()->id;
        $leave->data = json_encode($data);

        $leave->save();

How can I retrieve them if I want to display applicant_name from data field?

I am trying -

        $leave = Leave::find($leave_id);

        return $leave->data['applicant_name'];

If I dd($leave) then it gives me

    "id" => 2
    "user_id" => 7
    "data" => "{"applicant_name":"Mousumi Roy","post_held":"Administrative Officer Judicial","department":"Computer"}"
    "created_at" => "2020-04-25 17:38:25"
    "updated_at" => "2020-04-25 17:38:25"

Upvotes: 1

Views: 90

Answers (2)

Christophe Hubert
Christophe Hubert

Reputation: 2951

You can use an array casting for this, you can see in the doc: https://laravel.com/docs/7.x/eloquent-mutators#array-and-json-casting

in your model, use

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

then in your code, you don't need to use json_decode or json_encode, just:

        $leave = new Leave;
        $leave->data = $data;
        $leave->save();

And

        $leave = Leave::find($leave_id);
        return $leave->data['applicant_name'];

Upvotes: 2

Mohammad Hosseini
Mohammad Hosseini

Reputation: 1797

First You need to retrieve object for ex: $leave and then access to data with:

$data = $leave->data or $data = $leave['data']

but its encoded so try to decode that with $decoded = json_decode($data)

At the end you can access to applicant_name with $decoded->applicant_name

Upvotes: 0

Related Questions