Refactoring objects using Laravel Collections fails

Posted 1 year ago by eddieace

What I try to do is that I need to return an array with key-value pairs from an array of objects.

From an api I get objects that looks something like this.

    array:8 [▼
      0 => TargetingSearch {#229 ▼
        #data: array:6 [▼
          "id" => "6005609368513"
          "name" => "Software"
          "audience_size" => 565991450
          "path" => array:4 [▶]
          "description" => ""
          "topic" => "Technology"
        #_type_checker: TypeChecker {#228 ▶}

The simple way to do it is to loop through the objects and push the values into an array.

      $codes = [];
      foreach($objects as $object) {
          $codes[] = [
            'id' => $object->id,
            'name' => $object->name,

Which will return this that is exactly what I need.

    ['id' => 321, 'name' => "item1"],
    ['id' => 321, 'name' => "item1"],
    ['id' => 321, 'name' => "item1"],

I think that this is a little hard to manage and what I try to do is something a little more readable.

For example, by using the Laravel collection classes I could do something like this.

$codes = collect($objects)->pluck('id', 'name')->toArray();

The problem here is that this does not return the keys.

    ["item1" => "123"],
    ["item2" => "321"],
    ["item3" => "213"],

If I use

$codes = collect($objects)->only('id', 'name')->toArray(); 

It returns an empty array because the object itself is messing it all up.

anyone knows how to solve this?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.