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).
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 thefill
method, you can use theforceFill
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:Once we have the decoded data, we can create an instance of the
Post
eloquent model and callforceFill
on it:This is similar to doing:
Just turn it to array and fill an eloquent
Can you try it like this?
Hydrate model from array