Illuminate\Support\Collection::random PHP Method

random() public method

Get one or more items randomly from the collection.
public random ( integer $amount = 1 ) : mixed
$amount integer
return mixed
    public function random($amount = 1)
    {
        if ($amount > ($count = $this->count())) {
            throw new InvalidArgumentException("You requested {$amount} items, but there are only {$count} items in the collection");
        }
        $keys = array_rand($this->items, $amount);
        if ($amount == 1) {
            return $this->items[$keys];
        }
        return new static(array_intersect_key($this->items, array_flip($keys)));
    }

Usage Example

Exemplo n.º 1
0
 /**
  * Get either the predefined (subset of) collection/model, or.
  * @return Collection|mixed|BaseModel
  */
 private function getPredefinedOrMocks()
 {
     if ($this->entityCount > 1) {
         $collection = new Collection();
         if ($this->predefinedEntities) {
             if ($this->predefinedEntities instanceof Collection) {
                 $collection = $collection->merge($this->predefinedEntities->random($this->entityCount));
             } else {
                 $collection->push($this->predefinedEntities);
             }
         }
         if ($collection->count() < $this->entityCount) {
             /** @var Collection $collection */
             $collection = $collection->merge($this->getModelMock($this->entityCount - $collection->count()));
         }
         return $collection;
     } else {
         if ($this->predefinedEntities) {
             if ($this->predefinedEntities instanceof Collection) {
                 return $this->predefinedEntities->random();
             } else {
                 return $this->predefinedEntities;
             }
         }
         return $this->getModelMock();
     }
 }
All Usage Examples Of Illuminate\Support\Collection::random