Collection.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php namespace Illuminate\Database\Eloquent;
  2. use Illuminate\Support\Collection as BaseCollection;
  3. class Collection extends BaseCollection {
  4. /**
  5. * Find a model in the collection by key.
  6. *
  7. * @param mixed $key
  8. * @param mixed $default
  9. * @return \Illuminate\Database\Eloquent\Model
  10. */
  11. public function find($key, $default = null)
  12. {
  13. return array_first($this->items, function($key, $model)
  14. {
  15. return $model->getKey() == $key;
  16. }, $default);
  17. }
  18. /**
  19. * Load a set of relationships onto the collection.
  20. *
  21. * @param dynamic string
  22. * @return void
  23. */
  24. public function load()
  25. {
  26. if (count($this->items) > 0)
  27. {
  28. $query = $this->first()->newQuery()->with(func_get_args());
  29. $this->items = $query->eagerLoadRelations($this->items);
  30. }
  31. }
  32. /**
  33. * Add an item to the collection.
  34. *
  35. * @param mixed $item
  36. * @return \Illuminate\Database\Eloquent\Collection
  37. */
  38. public function add($item)
  39. {
  40. $this->items[] = $item;
  41. return $this;
  42. }
  43. /**
  44. * Determine if a key exists in the collection.
  45. *
  46. * @param mixed $key
  47. * @return bool
  48. */
  49. public function contains($key)
  50. {
  51. return ! is_null($this->find($key));
  52. }
  53. /**
  54. * Fetch a nested element of the collection.
  55. *
  56. * @param string $key
  57. * @return \Illuminate\Support\Collection
  58. */
  59. public function fetch($key)
  60. {
  61. return new static(array_fetch($this->toArray(), $key));
  62. }
  63. /**
  64. * Get the array of primary keys
  65. *
  66. * @return array
  67. */
  68. public function modelKeys()
  69. {
  70. return array_map(function($m) { return $m->getKey(); }, $this->items);
  71. }
  72. }