Search code examples
phplaravel-9

Laravel collection has not working as i expected?


I am trying to loop the array and find if a $value exists in it, I am using Laravel Collection for it. But I stumbled into an unexpected bug, am I doing something wrong? I already rood the documentation but I haven't found any solution there. I think I am going old school here with a normal loop. Collection is a good thing in Laravel, I hope that is my mistake.

Needle:

$value = "id";

Array to be looped:

 /**
 * Properties to be defined as private.
 *
 * @var array<string>
 */
protected array $privateData = [
    "id"
];

Not working :

/**
 * Return array with public elements
 * @return array $data
 */
public function toArray():array
{
    $data = [];
    foreach ($this->publicData as $value) 
    {
        if(!$this->includePrivateProperties)
        {
            if(!collect($this->privateData)->has($value)){
                $data[$value] = $this->get($value);
            }
        }
    }
    return $data;
}

Working:

 /**
 * Return array with public elements
 * @return array $data
 */
public function toArray():array
{
    $data = [];
    foreach ($this->publicData as $value) 
    {
        if(!$this->includePrivateProperties)
        {
            if(!in_array($value, $this->privateData))
            {
                $data[$value] = $this->get($value);
            }
        }
    }
    return $data;
}

Thank you for your help ! enter image description here


Solution

  • You should use contains to check if a value exists in collection.