Reputation: 27
I'm using Laravel 5 and MongoDB based Eloquent Jenssegers to develop an API to save and get data. I have a object called Player and inside I have other nested objects.
For example:
{
"idPlayer": "1",
"name": "John",
"lastname": "Doe",
"stats": {
"position": "lorem",
"profile": "ipsum",
"technique": {
"skill": 1
}
}
}
Using Postman to test I've could insert "idPlayer"
, "name"
and "lastname"
without problems, but I couldn't figure out how to insert stats inside the Player object.
This is what I've tried:
PlayerController.php
public function store(Request $request)
{
$player->name= $request->input('name');
$player->lastname = $request->input('lastname');
$player->save();
return response()->json($player);
}
And to insert stats I've tried to do something like this inside the store function:
$player->stats = $request->input('position');
$player->stats = $request->input('profile');
But I get "Stats:null"
on response and the name and lastname inserts ok.
I expect to insert the data just as the Player
object shown above.
Upvotes: 1
Views: 2036
Reputation: 8199
My workaround solution for Laravel.MongoDB:
$user = Player::firstOrCreate(['email' => strtolower($email)]);
$user->stats = array_merge( (array) $user->stats ?? [], ['key'=>'val']);
This will create stats
attribute if not exists or append in existing.
Upvotes: 0
Reputation: 7295
Make an array with keys.
public function store(Request $request)
{
$player->name = $request->input('name');
$player->lastname = $request->input('lastname');
$player->stats = [
'position' => $request->input('stats.position'),
'profile' => $request->input('stats.profile'),
];
$player->save();
return response()->json($player);
}
Upvotes: 2