How can I convert json to a Laravel Eloquent Model?

丶灬走出姿态 提交于 2019-11-28 00:13:32

问题


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' } }

To the relevant Post object that, once received in the controller, I can save to the database like this:

public function store(Post $post)
{
    $post->save();
}

I'm not looking to build the logic that would do that for me, but for the Laravel way (or could it be that there isn't one? I googled it with no relevant results).


回答1:


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



回答2:


fill looks like the method you want. To avoid adding every attribute to your $filled array, which you would need to do if you wanted to use the fill method, you can use the forceFill method.

It accepts an associative array of attributes, so the JSON will have to be decoded, and we'll have to get the inner post key:

$rawJson = "{ post: { text: 'my text' } }";
$decodedAsArray = json_decode($rawJson, true);
$innerPost = $decodedAsArray['post'];

Once we have the decoded data, we can create an instance of the Post eloquent model and call forceFill on it:

$post = new Post();
$post->forceFill($innerPost);
$post->save();

This is similar to doing:

$post = new Post();
foreach ($innerPost as $key => $value) {
    $post->$key = $value;
}
$post->save();



回答3:


Just turn it to array and fill an eloquent

$arr = json_decode($json, true);
$post = new Post;
$post->fill($arr);



回答4:


Can you try it like this?

public function store($poststuff)
{
    $post = new Post;
    $post->text = $poststuff['text'];
    $post->save();
}


来源:https://stackoverflow.com/questions/44730920/how-can-i-convert-json-to-a-laravel-eloquent-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!