How can I convert json to a Laravel Eloquent Model?

后端 未结 5 1560
無奈伤痛
無奈伤痛 2021-02-20 02:43

if I have an Eloquent Model called Post, and the mysql table has:

integer ID, string Text

How do I convert this JSon:

{ post: { text: \'my text\'         


        
5条回答
  •  不知归路
    2021-02-20 03:13

    1. Convert json to array
    2. Hydrate model from array

      $data = '{  
                  "unique_id_001":{"name":"John","email":"JD@stackoverflow.com"},
                  "unique_id_002":{"name":"Ken","email":"Ken@stackoverflow.com"}
                }';
      $object = (array)json_decode($data);
      $collection = \App\User::hydrate($object);
      $collection = $collection->flatten();   // get rid of unique_id_XXX
      
      /*
          Collection {#236 ▼
            #items: array:2 [▼
              0 => User {#239 ▶}
              1 => User {#240 ▶}
            ]
          }
       */
      dd($collection);
      

提交回复
热议问题