php Laravel 中的 MassAssignmentException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22280136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:48:02  来源:igfitidea点击:

MassAssignmentException in Laravel

phplaravel

提问by user1801060

I am a Laravel newbie. I want to seed my database. When I run the seed command I get an exception

我是 Laravel 新手。我想播种我的数据库。当我运行种子命令时,出现异常

  [Illuminate\Database\Eloquent\MassAssignmentException]
  username



db:seed [--class[="..."]] [--database[="..."]]

What am I doing wrong. The command I use is:

我究竟做错了什么。我使用的命令是:

php artisan db:seed --class="UsersTableSeeder"

My seed class is as follows:

我的种子类如下:

class UsersTableSeeder extends Seeder {
    public function run()
    {
            User::truncate();
            User::create([
                'username' => 'PaulSheer',
                'email' => '[email protected]',
                'password' => '45678'
            ]);

            User::create([
                'username' => 'Stevo',
                'email' => '[email protected]',
                'password' => '45678'
            ]);
    }
}

回答by Alexandre Butynski

Read this section of Laravel doc : http://laravel.com/docs/eloquent#mass-assignment

阅读 Laravel 文档的这一部分:http://laravel.com/docs/eloquent#mass-assignment

Laravel provides by default a protection against mass assignment security issues. That's why you have to manually define which fields could be "mass assigned" :

Laravel 默认提供针对大量赋值安全问题的保护。这就是为什么您必须手动定义哪些字段可以“批量分配”:

class User extends Model
{
    protected $fillable = ['username', 'email', 'password'];
}


Warning :be careful when you allow the mass assignment of critical fields like passwordor role. It could lead to a security issue because users could be able to update this fields values when you don't want to.

警告:当您允许对诸如password或之类的关键字段进行批量分配时要小心role。这可能会导致安全问题,因为用户可以在您不希望时更新此字段值。

回答by Pascalculator

I am using Laravel 4.2.

我正在使用 Laravel 4.2。

the error you are seeing

你看到的错误

[Illuminate\Database\Eloquent\MassAssignmentException]
username

indeed is because the database is protected from filling en masse, which is what you are doing when you are executing a seeder. However, in my opinion, it's not necessary (and might be insecure) to declare which fields should be fillable in your model if you only need to execute a seeder.

确实是因为数据库受到保护,不会被大量填充,这就是您在执行播种机时所做的事情。但是,在我看来,如果您只需要执行播种器,则没有必要(并且可能不安全)声明哪些字段应该可以填充到您的模型中。

In your seeding folder you have the DatabaseSeeder class:

在您的种子文件夹中,您有 DatabaseSeeder 类:

class DatabaseSeeder extends Seeder {

    /**
    * Run the database seeds.
    *
    * @return void
    */

    public function run()
    {
        Eloquent::unguard();

        //$this->call('UserTableSeeder');
    }
}

This class acts as a facade, listing all the seeders that need to be executed. If you call the UsersTableSeeder seeder manually through artisan, like you did with the php artisan db:seed --class="UsersTableSeeder"command, you bypass this DatabaseSeeder class.

此类充当门面,列出所有需要执行的播种机。如果您通过 artisan 手动调用 UsersTableSeeder 播种器,就像您使用php artisan db:seed --class="UsersTableSeeder"命令所做的那样,您将绕过这个 DatabaseSeeder 类。

In this DatabaseSeeder class the command Eloquent::unguard();allows temporary mass assignment on all tables, which is exactly what you need when you are seeding a database. This unguard method is only executed when you run the php aristan db:seedcommand, hence it being temporary as opposed to making the fields fillable in your model (as stated in the accepted and other answers).

在这个 DatabaseSeeder 类中,该命令Eloquent::unguard();允许对所有表进行临时批量分配,这正是您在为数据库做种时所需要的。此 unguard 方法仅在您运行php aristan db:seed命令时执行,因此它是临时的,而不是使您的模型中的字段可填写(如已接受的答案和其他答案中所述)。

All you need to do is add the $this->call('UsersTableSeeder');to the run method in the DatabaseSeeder class and run php aristan db:seedin your CLI which by default will execute DatabaseSeeder.

您需要做的就是$this->call('UsersTableSeeder');在 DatabaseSeeder 类中添加run 方法并php aristan db:seed在您的 CLI 中运行,默认情况下将执行 DatabaseSeeder。

Also notethat you are using a plural classname Users, while Laraval uses the the singular form User. If you decide to change your class to the conventional singular form, you can simply uncomment the //$this->call('UserTableSeeder');which has already been assigned but commented out by default in the DatabaseSeeder class.

另请注意,您使用的是复数的类名 Users,而 Laraval 使用的是单数形式的 User。如果您决定将您的类更改为传统的单数形式,您可以简单地取消注释//$this->call('UserTableSeeder');已经分配但默认在 DatabaseSeeder 类中注释掉的那些。

回答by Tiago Gouvêa

To make all fields fillable, just declare on your class:

要使所有字段都可填写,只需在您的班级上声明:

protected $guarded = array();

This will enable you to call fill method without declare each field.

这将使您能够在不声明每个字段的情况下调用 fill 方法。

回答by bicycle

Just add Eloquent::unguard();in the top of the run method when you do a seed, no need to create an $fillablearray in all the models you have to seed.

Eloquent::unguard();做种子时只需在 run 方法的顶部添加,无需$fillable在所有必须种子的模型中创建数组。

Normally this is already specified in the DatabaseSeederclass. However because you're calling the UsersTableSeederdirectly:

通常这已经在DatabaseSeeder类中指定。但是因为你UsersTableSeeder直接调用:

php artisan db:seed --class="UsersTableSeeder"

php artisan db:seed --class="UsersTableSeeder"

Eloquent::unguard();isn't being called and gives the error.

Eloquent::unguard();没有被调用并给出错误。

回答by parastoo amini

I used this and have no problem:

我用过这个,没有问题:

protected $guarded=[];

回答by Rahul Hirve

User proper model in your controller file.

在您的控制器文件中使用正确的模型。

<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;

回答by Amit Garg

I was getting the MassAssignmentException when I have extends my model like this.

当我像这样扩展我的模型时,我得到了 MassAssignmentException。

class Upload extends Eloquent {

}

I was trying to insert array like this

我试图插入这样的数组

Upload::create($array);//$array was data to insert.

Issue has been resolvewhen I created Upload Model as

当我将上传模型创建为时,问题已解决

class Upload extends Eloquent {
    protected $guarded = array();  // Important
}

Reference https://github.com/aidkit/aidkit/issues/2#issuecomment-21055670

参考https://github.com/aidkit/aidkit/issues/2#issuecomment-21055670

回答by DolDurma

if you have table and fields on database you can simply use this command :

如果您在数据库中有表和字段,您可以简单地使用以下命令:

php artisan db:seed --class=UsersTableSeeder --database=YOURDATABSE

回答by Sameer Shaikh

Use the fillableto tell laravel which fields can be filled using an array. By default, Laravel does not allow database fields to be updated via an array

使用可填写告诉laravel使用数组哪些字段即可充满。默认情况下,Laravel 不允许通过数组更新数据库字段

Protected $fillable=array('Fields you want to fill using array');

The opposite of fillableis guardable.

的相对可填充guardable

回答by Amin

This is not a good way when you want to seeding database.
Use fakerinstead of hard coding, and before all this maybe it's better to truncate tables.

当您想要播种数据库时,这不是一个好方法。
使用faker而不是硬编码,在这之前最好截断表格。

Consider this example :

考虑这个例子:

    // Truncate table.  
    DB::table('users')->truncate();

    // Create an instance of faker.
    $faker = Faker::create();

    // define an array for fake data.
    $users = [];

    // Make an array of 500 users with faker.
    foreach (range(1, 500) as $index)
    {
        $users[] = [
            'group_id' => rand(1, 3),
            'name' => $faker->name,
            'company' => $faker->company,
            'email' => $faker->email,
            'phone' => $faker->phoneNumber,
            'address' => "{$faker->streetName} {$faker->postCode} {$faker->city}",
            'about' => $faker->sentence($nbWords = 20, $variableNbWords = true),
            'created_at' => new DateTime,
            'updated_at' => new DateTime,
        ];
    }

    // Insert into database.
    DB::table('users')->insert($users);