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.

#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!
Laravel's Primary Function: Backend DevelopmentApr 15, 2025 am 12:14 AMLaravel's core functions in back-end development include routing system, EloquentORM, migration function, cache system and queue system. 1. The routing system simplifies URL mapping and improves code organization and maintenance. 2.EloquentORM provides object-oriented data operations to improve development efficiency. 3. The migration function manages the database structure through version control to ensure consistency. 4. The cache system reduces database queries and improves response speed. 5. The queue system effectively processes large-scale data, avoid blocking user requests, and improve overall performance.
Laravel's Backend Capabilities: Databases, Logic, and MoreApr 14, 2025 am 12:04 AMLaravel performs strongly in back-end development, simplifying database operations through EloquentORM, controllers and service classes handle business logic, and providing queues, events and other functions. 1) EloquentORM maps database tables through the model to simplify query. 2) Business logic is processed in controllers and service classes to improve modularity and maintainability. 3) Other functions such as queue systems help to handle complex needs.
Laravel's Versatility: From Simple Sites to Complex SystemsApr 13, 2025 am 12:13 AMThe Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.
Laravel (PHP) vs. Python: Development Environments and EcosystemsApr 12, 2025 am 12:10 AMThe comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.
Laravel and the Backend: Powering Web Application LogicApr 11, 2025 am 11:29 AMHow does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.
Why is Laravel so popular?Apr 02, 2025 pm 02:16 PMLaravel's popularity includes its simplified development process, providing a pleasant development environment, and rich features. 1) It absorbs the design philosophy of RubyonRails, combining the flexibility of PHP. 2) Provide tools such as EloquentORM, Blade template engine, etc. to improve development efficiency. 3) Its MVC architecture and dependency injection mechanism make the code more modular and testable. 4) Provides powerful debugging tools and performance optimization methods such as caching systems and best practices.
Which is better, Django or Laravel?Mar 28, 2025 am 10:41 AMBoth Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.
Which is better PHP or Laravel?Mar 27, 2025 pm 05:31 PMPHP and Laravel are not directly comparable, because Laravel is a PHP-based framework. 1.PHP is suitable for small projects or rapid prototyping because it is simple and direct. 2. Laravel is suitable for large projects or efficient development because it provides rich functions and tools, but has a steep learning curve and may not be as good as pure PHP.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Mac version
God-level code editing software (SublimeText3)







