How 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.
#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!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

How 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.

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.
