Search code examples
arraysjsonlaravelaccessor

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
        )
)

Solution

  • 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. :)