Pavel Prokofiev
Pavel Prokofiev

Reputation: 449

laravel collections->keyBy finds similar keys

laravel 5.5 here is the collections:

$collections = collect(['name' => 'Rob'], ['nickname' => 'Robby']);

the both methods:

$collections->keyBy('name')
$collections->keyBy('nickname')

return equil result

Collection {#246 ▼
  #items: array:1 [▼
    "" => "Rob"
  ]
}

as me this looks like wrong...

Upvotes: 1

Views: 1257

Answers (3)

aaron0207
aaron0207

Reputation: 2333

Your problem is that your collection is not well formatted, do it like this:

$collections = collect([ //main collection array
            [ 'name' => 'Rob1', 'nickname' => 'Robby1' ] //object 0 inside collection array with well formated keys => values
        ]);

Now when you use:

$collections->keyBy('name')
$collections->keyBy('nickname')

It will work as spected

Upvotes: 0

Pavel Prokofiev
Pavel Prokofiev

Reputation: 449

so results are

Collection {#246 ▼
  #items: array:2 [▼
    "Rob" => array:1 [▼
      "name" => "Rob"
    ]
    "" => array:1 [▼
      "nickname" => "Robby"
    ]
  ]
}

and

Collection {#246 ▼
  #items: array:2 [▼
    "" => array:1 [▼
      "name" => "Rob"
    ]
    "Robby" => array:1 [▼
      "nickname" => "Robby"
    ]
  ]
}

still looks invalid searching in collections... and

$collections->keyBy('nick')

returns

Collection {#246 ▼
  #items: array:1 [▼
    "" => array:1 [▼
      "nickname" => "Robby"
    ]
  ]
}

Upvotes: 0

Ali Beshir
Ali Beshir

Reputation: 432

I Think You Should pass one parameter as an array .. Try This

$collections = collect([['name' => 'Rob'], ['nickname' => 'Robby']]);

Upvotes: 1

Related Questions