/** * Add a tenant to scope by. * * @param string|Model $tenant * @param mixed|null $id */ public function addTenant($tenant, $id = null) { if (func_num_args() == 1) { $id = $tenant->getKey(); } $this->tenants->put($this->getTenantKey($tenant), $id); }
/** * @param array $data * @return bool */ public function insert(array $data = []) { $this->source->fill($data); if ($this->source->save()) { return $this->source->getKey(); } return false; }
/** * Set the base constraints on the relation query. * * @return void */ public function addConstraints() { $parentTable = $this->parent->getTable(); $this->setJoin(); if (static::$constraints) { $this->query->where($parentTable . '.' . $this->firstKey, '=', $this->farParent->getKey()); } }
/** * Save the resource in storage. * * @param string * @return Response */ protected function save($action) { // Set feedback message depending on action type switch ($action) { default: $successMessage = _('%s successfully saved'); $errorMessage = _('Unable to save %s'); break; case 'store': case '_store': $successMessage = _('%s successfully created'); $errorMessage = _('Unable to create %s'); break; case 'update': case '_update': $successMessage = _('%s successfully updated'); $errorMessage = _('Unable to update %s'); break; } // Persist to storage try { if (!$this->resource->save()) { throw new DomainException($errorMessage); } Session::flash('success', sprintf($successMessage, $this->resource)); return redirect()->route($this->route . '.show', [$this->resource->getKey()]); } catch (DomainException $e) { Session::flash('error', sprintf($e->getMessage(), $this->resource)); return redirect()->back()->withInput(); } }
/** * Removes a model from this relationship type. */ public function remove(Model $model, $sessionKey = null) { if ($sessionKey === null) { $this->detach($model->getKey()); } else { $this->parent->unbindDeferred($this->relationName, $model, $sessionKey); } }
/** * @param Model $user * * @return string */ public function encode(Model $user) { /** @var User $user */ $secret = str_random(); $token = json_encode([self::KEY_USER_ID => $user->getKey(), self::KEY_SECRET => $secret]); $user->{User::FIELD_API_TOKEN} = $secret; $user->saveOrFail(); return $token; }
/** * @param Model $oModel * @return array */ protected function resolveModelToArray(Model $oModel) { /** @var Key $oKey */ $oKey = $oModel->getAttribute("key"); /** @var Locale $oLocale */ $oLocale = $oModel->getAttribute("locale"); $aReturn = [$oModel->getKeyName() => $oModel->getKey(), "key" => $oKey ? $oKey->getAttribute(Key::COLUMN_NAME) : null, "locale" => $oLocale ? $oLocale->getAttribute(Locale::COLUMN_CODE) : null, Message::COLUMN_TEXT => $oModel->getAttribute(Message::COLUMN_TEXT)]; return $aReturn; }
/** * Delete a model document. * * @return mixed */ public function delete() { $this->exitIfModelNotSet(); $params = ['id' => $this->model->getKey(), 'type' => $this->model->getDocumentType(), 'index' => $this->model->getDocumentIndex()]; // check if the document exists before deleting if ($this->connection->existsStatement($params)) { return $this->connection->deleteStatement($params); } return true; }
public function associate($key, Model $model) { /** @var Collection $collection */ $collection = $this->relation->getParent()->{$key}; foreach ($collection as $position => $m) { // already in there if ($model === $m) { return; } if ($model->getKey() && $model->getKey() == $m->getKey()) { // found a different instance with the same key, substitute it $collection[$position] = $model; return; } } // if it get's to here, there's no matching model, so we just append the // new one at the end of the collection $collection[] = $model; }
/** * 生成查看详情按钮 GET方式跳转新页面 * @param CrudController $controller * @param Model $item * @return string */ public static function block_btn_show(CrudController $controller, Model $item) { $url = $controller->redirectToMethodUrl('getShow', $controller, [$item->getKey()]); $action = 'admin::' . $controller::getActionPrefix() . '.show.detail'; if (AdminAuthMiddleware::canAccess($action, \Auth::user())) { $disabled = ''; } else { $disabled = 'disabled'; } return "<a class='btn btn-sm btn-info gofarms-btn-actions' href='{$url}' target='_blank' {$disabled}><span class='glyphicon glyphicon-search'></span></a>"; }
/** * Get all of the queries that would be run for a migration. * * @param object $migration * @param string $method * * @return array */ protected function getQueries($migration, $method) { $connection = $migration->getConnection(); // Now that we have the connections we can resolve it and pretend to run the // queries against the database returning the array of raw SQL statements // that would get fired against the database system for this migration. $db = $this->resolveConnection($connection); return $db->pretend(function () use($migration, $method) { call_user_func([$migration, $method], $this->entity->getKey(), $this->entity); }); }
/** * Constrain a query to an ability for a specific model. * * @param \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder $query * @param \Illuminate\Database\Eloquent\Model $model * @return void */ public function scopeForModel($query, Model $model) { $query->where(function ($query) use($model) { $query->where('entity_type', $model->getMorphClass()); $query->where(function ($query) use($model) { $query->whereNull('entity_id'); if ($model->exists) { $query->orWhere('entity_id', $model->getKey()); } }); }); }
public function enviarImagem(Model $obj, $tipo, UploadedFile $file, $substituir = false) { //EXCLUINDO ANTIGA if ($substituir) { $imagens = $this->findWhere([$obj->getKeyName() => $obj->getKey(), 'imagem_tipo' => $tipo], ['imagem_id']); foreach ($imagens as $img) { $this->delete($img->imagem_id); } } $arquivo = $obj->gerarNomeHashArquivo($file); $file->move($obj->folderPath(), $arquivo['completo']); $tamanho = getimagesize($obj->folderPath() . '/' . $arquivo['completo']); list($largura, $altura) = getimagesize($obj->folderPath() . "/" . $arquivo['completo']); if ($largura < $this->model->sizes[$tipo][0] || $altura < $this->model->sizes[$tipo][1]) { $img = Image::make($obj->folderPath() . "/" . $arquivo['completo']); $img->resizeCanvas($this->model->sizes[$tipo][0], $this->model->sizes[$tipo][1], 'center'); $img->save($obj->folderPath() . "/" . $arquivo['completo']); $tamanho = getimagesize($obj->folderPath() . '/' . $arquivo['completo']); } $imagem = $this->create([$obj->getKeyName() => $obj->getKey(), 'imagem_tipo' => $tipo, 'imagem_nome' => $arquivo['completo'], 'imagem_largura' => $tamanho[0], 'imagem_altura' => $tamanho[1]]); return $imagem; }
/** * Get the constraint for the ability subquery. * * @param \Illuminate\Database\Eloquent\Model $model * @param bool $strict * @return \Closure */ protected function abilitySubqueryConstraint(Model $model, $strict) { return function ($query) use($model, $strict) { // If the model does not exist, we want to search for blanket abilities // that cover all instances of this model. If it does exist, we only // want to find blanket abilities if we're not using strict mode. if (!$model->exists || !$strict) { $query->whereNull($this->table . '.entity_id'); } if ($model->exists) { $query->orWhere($this->table . '.entity_id', $model->getKey()); } }; }
/** * Extract the model instance and model keys from the given parameters. * * @param string|\Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection $model * @param array|null $keys * @return array */ public static function extractModelAndKeys($model, array $keys = null) { if (is_null($keys)) { if ($model instanceof Model) { return [$model, [$model->getKey()]]; } if ($model instanceof Collection) { return [$model->first(), $model->modelKeys()]; } } else { if (is_string($model)) { $model = new $model(); } return [$model, $keys]; } }
/** * Records an activity * * @param Model $model * @param string $name * @param Model|int $user * @return Model */ public function record(Model $model = null, $name, $user = null) { if (!$this->isEnabled()) { return false; } $modelName = $this->getModelName(); $activity = new $modelName(); // Auto determine user if none is supplied $user = $this->getUserId($user); $data = ['name' => $name, 'user_id' => $user]; if ($model) { $data['subject_id'] = $model->getKey(); $data['subject_type'] = get_class($model); } $activity->fill($data); $activity->save(); return $activity; }
/** * Save a new model and attach it to the parent model. * * @param \Illuminate\Database\Eloquent\Model $model * @return \Illuminate\Database\Eloquent\Model */ public function performInsert(Model $model) { // Generate a new key if needed. if ($model->getKeyName() == '_id' and !$model->getKey()) { $model->setAttribute('_id', new MongoId()); } // For deeply nested documents, let the parent handle the changes. if ($this->isNested()) { $this->associate($model); return $this->parent->save(); } $result = $this->getBaseQuery()->update(array($this->localKey => $model->getAttributes())); // Attach the model to its parent. if ($result) { $this->associate($model); } return $result ? $model : false; }
/** * Associate the model instance to the given parent. * * @param \Illuminate\Database\Eloquent\Model $model * @return \Illuminate\Database\Eloquent\Model */ public function associate($model) { $this->parent->setAttribute($this->foreignKey, $model->getKey()); $this->parent->setAttribute($this->morphType, $model->getMorphClass()); return $this->parent->setRelation($this->relation, $model); }
/** * Retrieves an inventory stock from a given location. * * @param Model $location * * @throws StockNotFoundException * * @return mixed */ public function getStockFromLocation(Model $location) { $stock = $this->stocks()->where('location_id', $location->getKey())->first(); if ($stock) { return $stock; } else { $message = Lang::get('inventory::exceptions.StockNotFoundException', ['location' => $location->getAttribute('name')]); throw new StockNotFoundException($message); } }
/** * Creates a translation. * * @param Model $locale * @param string $text * @param Model $parentTranslation * * @return Model */ protected function firstOrCreateTranslation(Model $locale, $text, $parentTranslation = null) { // We'll check to see if there's a cached translation // first before we try and hit the database. $cachedTranslation = $this->getCacheTranslation($locale, $text); if ($cachedTranslation instanceof Model) { return $cachedTranslation; } // Check if auto translation is enabled. If so we'll run // the text through google translate and // save it, then cache it. if ($parentTranslation && $this->autoTranslateEnabled()) { $this->client->setSource($parentTranslation->locale->code); $this->client->setTarget($locale->code); try { $text = $this->client->translate($text); } catch (ErrorException $e) { // Request to translate failed, set the text // to the parent translation. $text = $parentTranslation->translation; } catch (UnexpectedValueException $e) { // Looks like something other than text was passed in, // we'll set the text to the parent translation // for this exception as well. $text = $parentTranslation->translation; } } if ($parentTranslation) { // If a parent translation is given we're looking for it's child translation. $translation = $this->translationModel->firstOrNew([$locale->getForeignKey() => $locale->getKey(), $this->translationModel->getForeignKey() => $parentTranslation->getKey()]); } else { // Otherwise we're creating the parent translation. $translation = $this->translationModel->firstOrNew([$locale->getForeignKey() => $locale->getKey(), 'translation' => $text]); } if (empty($translation->getAttribute('translation'))) { // We need to make sure we don't overwrite the translation // if it exists already in case it was modified. $translation->setAttribute('translation', $text); } if ($translation->isDirty()) { $translation->save(); } // Cache the translation so it's retrieved faster next time $this->setCacheTranslation($translation); return $translation; }
/** * Creates an upload record for the specified work order and uploaded file. * * @param Model $model * @param UploadedFile $file * @param BelongsToMany $relation * * @return \Stevebauman\Maintenance\Models\Attachment|bool */ public function create(Model $model, UploadedFile $file, BelongsToMany $relation) { $path = $this->getUploadPath($model->getKey()); $fileName = $this->getUniqueFileName($file); $storePath = $path . DIRECTORY_SEPARATOR . $fileName; $realPath = $file->getRealPath(); $contents = $realPath ? file_get_contents($realPath) : false; if ($contents && $this->storage->put($storePath, $contents)) { $attributes = ['user_id' => $this->sentry->getCurrentUserId(), 'name' => $file->getClientOriginalName(), 'file_name' => $file->getClientOriginalName(), 'file_path' => $storePath]; $attachment = $relation->create($attributes); if ($attachment) { return $attachment; } } return false; }
/** * Get older versions. * * @param Model $model * @param int $number number of versions * * @return Collection */ public function versions($model, $number = 25) { $query = $this->make(); return $query->whereHistorableId($model->getKey())->whereHistorableType(get_class($model))->whereNotNull('historable_json')->take($number)->order()->get(); }
/** * Associate the model instance to the given parent. * * @param \Illuminate\Database\Eloquent\Model $model * @return \Illuminate\Database\Eloquent\Model */ public function associate(Model $model) { $this->parent->setAttribute($this->foreignKey, $model->getKey()); return $this->parent->setRelation($this->relation, $model); }
/** * @param Model $user */ public function restored(Model $user) { $this->mixPanel->identify($user->getKey()); $this->mixPanel->track('User', ['Status' => 'Reactivated']); }
/** * Updates a model with the latest permissions, links, and fields * * @param \Illuminate\Database\Eloquent\Model $model * @param \Frozennode\Administrator\Fields\Factory $fieldFactory * @param \Frozennode\Administrator\Actions\Factory $actionFactory * * @return \Illuminate\Database\Eloquent\Model */ public function updateModel($model, FieldFactory $fieldFactory, ActionFactory $actionFactory) { //set the data model to the active model $this->setDataModel($model->find($model->getKey())); //include the item link if one was supplied if ($link = $this->getModelLink()) { $model->setAttribute('admin_item_link', $link); } //set up the model with the edit fields new data $model->setAttribute('administrator_edit_fields', $fieldFactory->getEditFieldsArrays(true)); //set up the new actions data $model->setAttribute('administrator_actions', $actionFactory->getActionsOptions(true)); $model->setAttribute('administrator_action_permissions', $actionFactory->getActionPermissions(true)); return $model; }
public function getUrl(Model $model) { return URL::route('admin.elegant.elegant.edit', ['elegant_model' => $this->getSlug(), $model->getKey()]); }
/** * Save a new model and attach it to the parent model. * * @param \Illuminate\Database\Eloquent\Model $model * @param array $joining * @param bool $touch * @return \Illuminate\Database\Eloquent\Model */ public function save(Model $model, array $joining = array(), $touch = true) { $model->save(array('touch' => false)); $this->attach($model->getKey(), $joining, $touch); return $model; }
/** * Resolve table name. * * @param \Illuminate\Database\Eloquent\Model $entity * @param string|null $name * * @return string|null */ protected function bindWithKey(Model $entity, $name) { if (is_null($name) || strpos($name, '{') === false && strpos($name, '}') === false) { return $name; } $id = $entity->getKey(); if (!isset($this->data[$id])) { $data = array_merge(Arr::dot(['entity' => $entity->toArray()]), compact('id')); $this->data[$id] = $data; } return Str::replace($name, $this->data[$id]); }
/** * Constrain a related query to the given user. * * @param \Illuminate\Database\Eloquent\Model $user * @return \Closure */ protected function getUserConstraint(Model $user) { return function ($query) use($user) { $column = "{$user->getTable()}.{$user->getKeyName()}"; $query->where($column, $user->getKey()); }; }
/** * Clear the cache for the given user. * * @param \Illuminate\Database\Eloquent\Model|int $user * @return $this */ public function refreshFor($user) { $id = $user instanceof Model ? $user->getKey() : $user; $this->cache->forget($this->tag . '-permissions-' . $id); $this->cache->forget($this->tag . '-roles-' . $id); return $this; }