Home  >  Article  >  PHP Framework  >  How to use laravel's fill method

How to use laravel's fill method

WBOY
WBOYOriginal
2022-06-06 15:33:233642browse

In laravel, the fill method is a method for assigning attributes to Eloquent instances. This method can be understood as being used to filter the redundant fields transmitted by the front end that correspond to the model; when this method is called, it will first To detect the status of the current Model, the Model will be in different states according to the settings of the fillable array.

How to use laravel's fill method

#The operating environment of this article: Windows 10 system, Laravel version 6, Dell G3 computer.

How to use laravel's fill method

The fill method is a method for assigning attributes to Eloquent instances.

Let's click on the fill method and take a look at its source code first: Array

The version used by the author here is the latest version of Laravel 5.5. For the convenience of reading, the annotation frame has been deleted

public function fill(array $attributes)
{
    $totallyGuarded = $this->totallyGuarded();
    foreach ($this->fillableFromArray($attributes) as $key => $value) {
        $key = $this->removeTableFromKey($key);
        if ($this->isFillable($key)) {
            $this->setAttribute($key, $value);
        } elseif ($totallyGuarded) {
            throw new MassAssignmentException($key);
        }
    }
    return $this;
}

First of all, you can see that Laravel will first call its own totallyGuarded method. , let us click on this method: Function

public function totallyGuarded()
{
   return count($this->getFillable()) == 0 && $this->getGuarded() == ['*'];
}

You can see that the function of this method is to obtain its own fillable and guarded, and then determine whether they are both in a non-batch assignable state, and finally return a Boolean value this

// 返回一个 True or False 的布尔值
// 若是未设置 fillable 与 guarded,则会返回 True (注意,在这种状况下,此 `Model` 是不容许批量赋值任何属性的哦)
// 反之则返回 False
$totallyGuarded = $this->totallyGuarded();

Ok, let’s go back to the fill method just now and continue to look at the design

The next step is a foreach loop, but before the loop, Laravel executes fillableFromArray on the incoming assignment attribute Click on this method to take a look, code

protected function fillableFromArray(array $attributes)
{
    if (count($this->getFillable()) > 0 && ! static::$unguarded) {
        return array_intersect_key($attributes, array_flip($this->getFillable()));
    }
    return $attributes;
}

This method will detect whether you have defined a value in the fillable array. If a value is defined, it will return the value of the intersection between fillable and attributes. If not, then Return the attributes own event

and then return to fill. After calling fillableFromArray to process the parameters, the returned values ​​​​are now only the attributes that we allow batch assignment (if you define them) ip

Loop the first line, first use removeTableFromKey to process the Key of the parameter, and delete the table name in the key. This method will not be explained too much. It is just a function for string splitting and value rem

$key = $this->removeTableFromKey($key);

and then proceed Looking below, Laravel calls the isFillable method for each attribute to be filled to ensure that this attribute can be filled. Let us take a look at its source code:

public function isFillable($key)
{
   if (static::$unguarded) {
       return true;
   }
   if (in_array($key, $this->getFillable())) {
       return true;
   }
   if ($this->isGuarded($key)) {
       return false;
   }
   return empty($this->getFillable()) &&
       ! Str::startsWith($key, '_');
}

You can see that in this method In Laravel, it first determines whether the guard is disabled for this Model. If the guard is not enabled for this Model, it will directly return True

if (static::$unguarded) {
    return true;
}

If the guard is enabled, it will determine whether this attribute exists in the fillable array. , if it exists, it returns True.

if (in_array($key, $this->getFillable())) {
    return true;
}

If this property does not exist in the fillable array, then Laravel will again determine whether this property exists in the guarded array. If it exists in this array, then this property It is not an attribute that can be assigned in batches, so it will directly return False

if ($this->isGuarded($key)) {
    return false;
}

If none of the above are met, then Laravel will finally determine whether its fillable array is empty and this attribute starts with _ , and then return a Boolean value

return empty($this->getFillable()) && ! Str::startsWith($key, '_');

Then return to the fill method and continue to see. If this attribute has been filtered by the isFillable method, then assign this attribute to itself (due to limited time, the setAttribute method will not be discussed in detail. La~),

$this->setAttribute($key, $value);

If it is not filtered by the isFillable method, then Laravel will determine whether its own Model is in a state that does not restrict batch assignment of any attributes. If not, then Laravel will directly throw an Exception

// 判断此属性是否经过了检测
if ($this->isFillable($key)) {
    // 将此属性赋值给自身
    $this->setAttribute($key, $value);
// 若是没有经过检测,那么判断一下自身 `Model` 是否为所有不可批量赋值状态,若是是,那么会抛出一个 `Exception`
} elseif ($totallyGuarded) {
    throw new MassAssignmentException($key);
}

After detecting and assigning all attributes, Laravel will return itself

return $this;

After parsing, the above is the source code of the fill method~, finally Let’s give a summary

When you call the fill method, Laravel will first detect the status of the current Model.

When you set the fillable array but not the guarded array, Then this Model will be in a state where only specified attributes can be assigned in batches

When you do not set a fillable array, but set a guarded array, then this Model will be in a state where any attributes can be assigned in batches

I won’t discuss the situation where you set up fillable and guarded arrays at the same time, because doing so is prohibited by Laravel.

Then call fillableFromArray to get the intersection of attributes and fillable arrays. If If you do not define fillable or disable the guard, then this method will directly return attributes

and then Laravel will make a loop on the returned array. In this loop, Laravel will call the isFillable method for each attribute to detect this attribute. Whether it can be filled, if it is not detected by this method (does not exist in the fillable array and does not set a guarded array or exists in a guarded array), then Laravel will check whether the current Model is in a state where only specified attributes can be assigned in batches. If so , then an Exception will be thrown directly

and Laravel will return $this

after completing the assignment operation [Related recommendation: laravel video tutorial]

The above is the detailed content of How to use laravel's fill method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn