1

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.

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer. Now it show Stats, but the attributes inside are null. It's like it can't read the position and profile.
Opps, you need to use stats.position to get the data. See here for more information: laravel.com/docs/5.1/requests#retrieving-input
Ohh, I see, thank you very much. I get confused because in PHP the dot concatenates. Works now.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.