kassir123's avatar

Use map on Laravel single instance

I want to map object property user to its name. I'm trying to map it like that, but it's doesn't change anything.

My code for getting results:

$data = $stats
    ->with('user')
    ->get()
    ->map(function ($value, $key) {
        $value['user'] = $value['user']['name'];
        return $value;
    });

Current resulted data:

{
    "data": [
        {
            "total": 4,
            "user": {
                "id": 3,
                "name": "test1"
            }
        }
    ]
}

Desired result:

{
    "data": [
        {
            "total": 4,
            "user": "test1"
        }
    ]
}
0 likes
4 replies
tisuchi's avatar

@kassir123

Wouldn't this work, if you add inside your map function return $value['user']['name']?

7 likes
kassir123's avatar

@tisuchi your code gives me only array of each user name without total, so that's not it.

5 likes
tisuchi's avatar
tisuchi
Best Answer
Level 70

@kassir123

That's what I mean-

$data = $stats
    ->with('user')
    ->get()
    ->map(function ($value, $key) {
        return [
            'total' => $value['total'],
            'user' => $value['user']['name'],
        ];
    });
8 likes

Please or to participate in this conversation.