Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert json to a Laravel Eloquent Model?

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

like image 354
Zephram Avatar asked Jun 23 '17 22:06

Zephram


1 Answers

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

    $data = '{  
                "unique_id_001":{"name":"John","email":"[email protected]"},
                "unique_id_002":{"name":"Ken","email":"[email protected]"}
              }';
    $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);
    
like image 195
Bartłomiej Sobieszek Avatar answered Sep 30 '22 21:09

Bartłomiej Sobieszek