search
HomePHP FrameworkLaravelHow to use laravel's fill method

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
Integrating JavaScript Frameworks (React, Vue, Angular) with a Laravel BackendIntegrating JavaScript Frameworks (React, Vue, Angular) with a Laravel BackendMay 03, 2025 am 12:20 AM

React,Vue,andAngularcanbeintegratedwithLaravelbyfollowingspecificsetupsteps.1)ForReact:InstallReactusingLaravelUI,setupcomponentsinapp.js.2)ForVue:UseLaravel'sbuilt-inVuesupport,configureinapp.js.3)ForAngular:SetupAngularseparately,servethroughLarave

Task Management Tools: Prioritizing and Tracking Progress in Remote ProjectsTask Management Tools: Prioritizing and Tracking Progress in Remote ProjectsMay 02, 2025 am 12:25 AM

Taskmanagementtoolsareessentialforeffectiveremoteprojectmanagementbyprioritizingtasksandtrackingprogress.1)UsetoolslikeTrelloandAsanatosetprioritieswithlabelsortags.2)EmploytoolslikeJiraandMonday.comforvisualtrackingwithGanttchartsandprogressbars.3)K

How does the latest Laravel version improve performance?How does the latest Laravel version improve performance?May 02, 2025 am 12:24 AM

Laravel10enhancesperformancethroughseveralkeyfeatures.1)Itintroducesquerybuildercachingtoreducedatabaseload.2)ItoptimizesEloquentmodelloadingwithlazyloadingproxies.3)Itimprovesroutingwithanewcachingsystem.4)ItenhancesBladetemplatingwithviewcaching,al

Deployment Strategies for Full-Stack Laravel ApplicationsDeployment Strategies for Full-Stack Laravel ApplicationsMay 02, 2025 am 12:22 AM

The best full-stack Laravel application deployment strategies include: 1. Zero downtime deployment, 2. Blue-green deployment, 3. Continuous deployment, and 4. Canary release. 1. Zero downtime deployment uses Envoy or Deployer to automate the deployment process to ensure that applications remain available when updated. 2. Blue and green deployment enables downtime deployment by maintaining two environments and allows for rapid rollback. 3. Continuous deployment Automate the entire deployment process through GitHubActions or GitLabCI/CD. 4. Canary releases through Nginx configuration, gradually promoting the new version to users to ensure performance optimization and rapid rollback.

Scaling a Full-Stack Laravel Application: Best Practices and TechniquesScaling a Full-Stack Laravel Application: Best Practices and TechniquesMay 02, 2025 am 12:22 AM

ToscaleaLaravelapplicationeffectively,focusondatabasesharding,caching,loadbalancing,andmicroservices.1)Implementdatabaseshardingtodistributedataacrossmultipledatabasesforimprovedperformance.2)UseLaravel'scachingsystemwithRedisorMemcachedtoreducedatab

The Silent Struggle: Overcoming Communication Barriers in Distributed TeamsThe Silent Struggle: Overcoming Communication Barriers in Distributed TeamsMay 02, 2025 am 12:20 AM

Toovercomecommunicationbarriersindistributedteams,use:1)videocallsforface-to-faceinteraction,2)setclearresponsetimeexpectations,3)chooseappropriatecommunicationtools,4)createateamcommunicationguide,and5)establishpersonalboundariestopreventburnout.The

Using Laravel Blade for Frontend Templating in Full-Stack ProjectsUsing Laravel Blade for Frontend Templating in Full-Stack ProjectsMay 01, 2025 am 12:24 AM

LaravelBladeenhancesfrontendtemplatinginfull-stackprojectsbyofferingcleansyntaxandpowerfulfeatures.1)Itallowsforeasyvariabledisplayandcontrolstructures.2)Bladesupportscreatingandreusingcomponents,aidinginmanagingcomplexUIs.3)Itefficientlyhandleslayou

Building a Full-Stack Application with Laravel: A Practical TutorialBuilding a Full-Stack Application with Laravel: A Practical TutorialMay 01, 2025 am 12:23 AM

Laravelisidealforfull-stackapplicationsduetoitselegantsyntax,comprehensiveecosystem,andpowerfulfeatures.1)UseEloquentORMforintuitivebackenddatamanipulation,butavoidN 1queryissues.2)EmployBladetemplatingforcleanfrontendviews,beingcautiousofoverusing@i

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)