Пример #1
0
 /**
  * @param Collection|BaseModel $modelOrCollection
  * @param Request $request
  * @return mixed
  */
 protected function getWithNested($modelOrCollection, Request $request)
 {
     if (!$modelOrCollection instanceof BaseModel && !$modelOrCollection instanceof Collection) {
         throw new \InvalidArgumentException('Model must be instance of Model or Collection');
     }
     $nested = $request->headers->get('With-Nested');
     if (!$nested) {
         return $modelOrCollection;
     }
     $requestedRelations = explode(', ', $nested);
     try {
         $modelOrCollection->load($requestedRelations);
     } catch (\BadMethodCallException $e) {
         throw new BadRequestException(sprintf('Invalid `With-Nested` request - one or more of the following relationships do not exist for %s:[%s]', get_class($modelOrCollection), $nested), null, $e);
     }
     return $modelOrCollection;
 }
Пример #2
0
 /**
  * Create a collection of models from a request collection
  * The method is more efficient if is passed a Collection of existing entries otherwise it will do a query for every entity
  *
  * @param  array $requestCollection
  * @param Collection $existingModels
  * @return \Illuminate\Database\Eloquent\Collection
  */
 public function hydrateRequestCollection(array $requestCollection, Collection $existingModels = null)
 {
     $keyName = $this->getKeyName();
     $models = array_map(function ($item) use($keyName, $existingModels) {
         $model = null;
         $entityId = $item[$keyName];
         if ($existingModels) {
             //get the model from the collection, or create a new instance
             $model = $existingModels->get($entityId, function () {
                 //using a closure, so new instance is only created when the default is required
                 return $this->newInstance();
             });
         } else {
             $this->findOrNew($entityId);
         }
         $model->fill($item);
         return $model;
     }, $requestCollection);
     return $this->newCollection($models);
 }