How can I convert json to Laravel Eloquent Model?

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

integer identifier, string Text

How do I convert this JSon:

{ post: { text: 'my text' } }

      

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

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

      

I'm not going to build logic that will do this for me, but for the Laravel path (or maybe there is no one there? I searched for it with no relevant results).

+3


source to share


4 answers


  • Json to array conversion
  • Solid hydrate model

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



+3


source


Just turn it into an array and fill eloquent



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

      

+1


source


Can you try it like this?

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

      

0


source


fill

looks like the method you want. To avoid adding each attribute to the array $filled

you will need to do if you want to use the method fill

you can use forceFill

.

It takes an associative array of attributes, so the JSON will need to be decoded and we need to get the internal key post

:

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

      

Once we have the decoded data, we can instantiate the post

eloquent model and call forceFill

on it:

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

      


It looks like doing:

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

      

0


source







All Articles