How to convert an json data in array using accessor method in Laravel?

I m new in Laravel 8. Please give any suggestion for the given below code or answer my question:
Given below is my code an example of what i really want to get:
my data is :

[{"column_1_1":"value_1_1","column_1_2":"value_1_2"},{"column_2_1":"value_2_1","column_2_2":"value_2_2"}]

and I want

Array
(
    [0] => stdClass Object
        (
            [column_1_1] => value_1_1
            [column_1_2] => value_1_2
        )
    [1] => stdClass Object
        (
            [column_2_1] => value_2_1
            [column_2_2] => value_2_2
        )
)

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I am adding this answer as the other is showing only one way and is the least used… Mine is the Laravel way, the one you should always use and the most you are going to see all the time…

If you have a Model who’s property is, for example, data, you don’t have to overwrite how it is read by doing getDataAttribute and use json_decode

If that property/field is a JSON/TEXT in your database (hence storing JSON), you just have to cast it.

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

So later you can do:

foreach ($model->data as $item) {
    ...
}

And store info in it like:

$array = ['products' => [item1', 'item2'], 'quantity' => 2];

$model->data = $array;

And it will get saved on the database like {products: ["item1", "item2"], quantity: 2}

Method 2

Bro you just need to add the accessor method in your model like:

Guess you have xyz column in your database

public function getXyzAttribute($xyz)
{
    return json_decode($xyz);
}

It will directly return the array.

Hope it worked. 🙂


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x