Search code examples
phplaravelobjectshorthand

php shorthand to append to object


I'm pulling through data from my database and wish to add an object to the end of each item. The following code works, but I'm assuming there's a better way than repeating all the info and adding to a new object.

    $cs = $client->contact()->get();

    foreach ($cs as $c) {

        $contact = (object)[
        'id' => $c->id,
        'name' => $c->name,
        'role' => $c->role,
        'phone' => $c->phone,
        'address' => $c->address,
        'postcode' => $c->postcode,
        'otherClients' => Contact::find($c->id)->clients()->get(), //this is the additional info
        ];

        $contacts[]=$contact;

Solution

  • You could simply mutate the original objects if you don't need to leave $cs intact.

    foreach ($cs as $c) {
        $c->otherClients = Contact::find($c->id)->clients()->get();
    }