Search code examples
phplaraveleloquentlaravel-collection

How to map object to single value from this object?


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"
        }
    ]
}

Solution

  • Like this:

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