Laravel 4 mass assignment guarded not work

懵懂的女人 提交于 2019-12-04 20:53:48

Actually you are not using Eloquent ORM and hence the following code guards mass assignment of Eloquent models, for example using Model::create(Input::all()) method you may create a new Account in the database like:

$account = Account::create(Input::all());

In your case, you are not using Eloquent model, instead you are using insert method using DB::('accounts')->insert($input) which is a feature of Query builder class (It's an instance of Illuminate\Database\Query\Builder).

So, if you use the Eloquent ORM then the features of Eloquent will be used. In this case, use of Model::save() is not a mass assignment but create() uses the mass assignment because when creating a new model, you may pass an array of attributes to the model constructor. These attributes are then assigned to the model via mass-assignment and create accepts an array of attributes and then initializes the model using new static($attributes), for example, this is the create method:

public static function create(array $attributes)
{
    $model = new static($attributes);
    $model->save();
    return $model;
}

So, if you manually initiate a model using something like this:

$account = new Account(Input::all()); // Mass assignment through constructor
$account->save();

This will be a mass assignment. In this case you need to create the Account model by extending the Eloquent like this (You already have one):

class Account extends Eloquent {

    // Protect mass assignment
    protected $guarded = array('username', 'password');

    //...
}

You may read more about Mass Assignment on Laravel website.

You are not using the Eloquent ORM. If you don't use the ORM you can't expect any of its features to be used.

DB::table('accounts')->insert($input);

Should be

$account = new Account($input);
$account->save():
// This is mass assigning model attributes

Now you will see that your guarded attributes are properly guarded. It is recommended that you do not pass raw input data into a model that has guarded attributes set without defining them either as fillable or making sure you specifically sanitise the data.

So your code would become something similar to the below.

$model = new Account();

$model->username = Input::get('username', '');
//  etc ...

$validator = Validator::make($model->toArray(), $rules);

if ( ! $validator->fails() )
    $model->save();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!