Problem Description
When using the seed function of laravel, there are often students who see the following exception
[Illuminate\database\eloquent\massassignmentexception]
Username
What is this exception? This means that when using model::create () This method, laravel to ensure the security of the system, to prevent malicious people through the HTTP request to direct the creation of certain fields directly into the database, causing corruption.
Citing the official website's exact words
A mass-assignment vulnerability occurs when user's pass unexpected HTTP parameters through a request, and then that Parame ter changes a column in your database do not expect. For example, a malicious user might send an is_admin parameter through an HTTP request, which was then mapped onto your mod El ' s create method, allowing the user to escalate themselves to an administrator.
Correct use
First, let's assume our seeder is like this.
Public Function Run () { db::table (' addresss ')->delete (); Address::create ([ ' user_id ' = + 1, ' identity ' = + 1, ' longlat ' = ' XXXXX ', ' province ' and ' = ') xxx ', ' city ' = ' xxx ', ' district ' + ' xxx ', ' detail ' = ' XXXX ', ]; }
At this point, if the Address model does not have a fillable or guarded two attributes, it is used directly
PHP artisan db:seed--class= "Addresstableseeder", the above error will be reported. Assume that Fillable is set in Address
protected $fillable = [' user_id ', ' identity ',];
If you execute the seed command at this point, the newly added data in the database will only have the user_id and identity fields.
Through the above process can clearly understand the meaning of the bulk assignment. So if you want to do all the data insertion when you create it, you should set all the fields to fillable.
what to do with too many fields
Occasionally also encounter a table in the field too much, a classmate said one by one write to fillable is not too egg broken ah. Laravel the most elegant frame in history, how could it not be taken into account? All there is a guarded this attribute for you to use. When there are too many fields, you can set the field that you want to disallow the batch assignment to inside.
There is no more. Continue to refuel, and have recently started using Laravel in the backend services of the app. Have shared some of their own tools to incorporate third-party SDK retrofits.
Baidu News push Laravel composer pack
Automatically generate API interface documentation Laravel Composer Package
Baidu Rich Text Tool Laravel composer bag
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.