samedi 25 février 2017

how to pull json data from data mysql as object using laravel5

I have a table which contain json in a column that i have to get as an object but when i pull data using laravel model then it obviously return as json or string which i have to decode every where, where i use this model(this is not dry concept) but the thing is if i pull one recored and one place then it is only one execution of code and ok but what if i have to pull collection of the data and multiple place then i have to run same decode every time is there any way in laravel that can do for me insted of using self made loop

here is the table

+-----------------------------------------------------------------------------+
|                                   table                                     |
+-----------------------------------------------------------------------------+
|id | title | text                                                            |
+-----------------------------------------------------------------------------+
| 1 |   A1  | {"subject":"Subject1","word":"Lorem ipsum dolor sit amet, ..."} |
| 2 |   A2  | {"subject":"Subject2","word":"Lorem ipsum dolor sit amet, ..."} |
| 3 |   A3  | {"subject":"Subject3","word":"Lorem ipsum dolor sit amet, ..."} |
| 4 |   A4  | {"subject":"Subject4","word":"Lorem ipsum dolor sit amet, ..."} |
| 5 |   A5  | {"subject":"Subject5","word":"Lorem ipsum dolor sit amet, ..."} |
| 6 |   A6  | {"subject":"Subject6","word":"Lorem ipsum dolor sit amet, ..."} |
| 7 |   A7  | {"subject":"Subject7","word":"Lorem ipsum dolor sit amet, ..."} |
| 8 |   A8  | {"subject":"Subject8","word":"Lorem ipsum dolor sit amet, ..."} |
| 9 |   A9  | {"subject":"Subject9","word":"Lorem ipsum dolor sit amet, ..."} |
| 10|  A10  | {"subject":"Subject10","word":"Lorem ipsum dolor sit amet..."}  |
+-----------------------------------------------------------------------------+


Result what i want

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [title] => A1
            [text] => stdClass Object
                (
                    [subject] => Subject1
                    [word] => Lorem ipsum dolor sit amet...
                )

        )

    [1] => stdClass Object
        (
            [id] => 2
            [title] => A2
            [text] => stdClass Object
                (
                    [subject] => Subject2
                    [word] => Lorem ipsum dolor sit amet...
                )

        )

    ...
)

if is there any easy way to that which is more efficient and follow dry then share with me

Thanks in advance.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire