How can I convert json to a Laravel Eloquent Model?

后端 未结 5 1532
無奈伤痛
無奈伤痛 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-20 03:05

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

提交回复
热议问题