Illuminate\Database\Eloquent\Model::setAttribute PHP Method

setAttribute() public method

Set a given attribute on the model.
public setAttribute ( string $key, mixed $value )
$key string
$value mixed
    public function setAttribute($key, $value)
    {
        // First we will check for the presence of a mutator for the set operation
        // which simply lets the developers tweak the attribute as it is set on
        // the model, such as "json_encoding" an listing of data for storage.
        if ($this->hasSetMutator($key)) {
            $method = 'set' . Str::studly($key) . 'Attribute';
            return $this->{$method}($value);
        } elseif ($value && (in_array($key, $this->getDates()) || $this->isDateCastable($key))) {
            $value = $this->fromDateTime($value);
        }
        if ($this->isJsonCastable($key) && !is_null($value)) {
            $value = $this->asJson($value);
        }
        // If this attribute contains a JSON ->, we'll set the proper value in the
        // attribute's underlying array. This takes care of properly nesting an
        // attribute in the array's value in the case of deeply nested items.
        if (Str::contains($key, '->')) {
            return $this->fillJsonAttribute($key, $value);
        }
        $this->attributes[$key] = $value;
        return $this;
    }

Usage Example

Example #1
1
 /**
  * Removes a model from this relationship type.
  */
 public function remove(Model $model, $sessionKey = null)
 {
     if ($sessionKey === null) {
         $options = $this->parent->getRelationDefinition($this->relationName);
         if (array_get($options, 'delete', false)) {
             $model->delete();
         } else {
             /*
              * Make this model an orphan ;~(
              */
             $model->setAttribute($this->getPlainForeignKey(), null);
             $model->setAttribute($this->getPlainMorphType(), null);
             $model->save();
         }
         /*
          * Use the opportunity to set the relation in memory
          */
         if ($this instanceof MorphOne) {
             $this->parent->setRelation($this->relationName, null);
         } else {
             $this->parent->reloadRelations($this->relationName);
         }
     } else {
         $this->parent->unbindDeferred($this->relationName, $model, $sessionKey);
     }
 }
All Usage Examples Of Illuminate\Database\Eloquent\Model::setAttribute
Model