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).
source to share
- 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);
source to share
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();
source to share