1
votes

I have small Laravel project working on collection editing. I have eloquent as below.

public function Import(){
    $org = LabGroup::get();
    return $org;
}

The returned result as below,

[
{
id: 1,
uuid: "491cd440-79d0-11e9-a294-b93a2fd40038",
branch: 0,
name: "productA",
},
{
id: 2,
uuid: "491d0b70-79d0-11e9-aba8-4d9cdb66858f",
branch: 0,
name: "productB",
},
{
id: 3,
uuid: "491d0c20-79d0-11e9-a243-0d208e55c95a",
branch: 0,
name: "productC",
}
]

My need is to change all branch value from 0 to 1. I can do by loop through but I may use other better like 'map' that I'm not familiar. Any advise or guidance would be greatly appreciated, Thanks.

2

2 Answers

1
votes

You can use map() in this way:

$org = LabGroup::get();

$org_branch_1 = $org->map(function ($item, $key) {
    return [
        'id' => $item->id,
        'uuid' => $item->uuid,
        'branch' => 1,
        'name' => $item->name,
    ];
});

return $org_branch_1;

If you don't need the original collection you can use transform() in the same way:

$org = LabGroup::get();

return $org->transform(function ($item, $key) {
    return [
        'id' => $item->id,
        'uuid' => $item->uuid,
        'branch' => 1,
        'name' => $item->name,
    ];
});

EDIT:
This will work too:

return LabGroup::get()->transform(function ($item, $key) {
                $item->branch = 1;
                return $item;
            });
0
votes

You can use eloquent update() method on your query:

$updatedOrg = LabGroup::get()->update(['branch' => 1]);
return $updatedOrg; \\Returns the result with the updated branch value.