/** * @param Builder $builder * @param Collection $tags * @return Builder */ public function scopeTaggedWith(Builder $builder, Collection $tags) { /** @var MorphToMany $relation */ $relation = $this->tags(); $key = $this->getTable() . '.' . $this->getKeyName(); if ($tags->count()) { $builder->join($relation->getTable(), function ($join) use($relation, $key, $tags) { $join->on($relation->getForeignKey(), '=', $key); $join->where($relation->getMorphType(), '=', $relation->getMorphClass()); $join->whereIn($relation->getOtherKey(), $tags->keys()->toArray()); }); } else { $builder->whereNull($this->getTable()); } return $builder; }
public static function choose_from_collection(\Illuminate\Database\Eloquent\Collection $collection) { assert($collection->count(), 'Collection empty!'); return $collection->get($collection->keys()[mt_rand() % $collection->count()]); }