Laravel5.8 报错MassAssignmentException

Laravel传递数据的时候报错MassAssignmentException

        foreach ($this->fillableFromArray($attributes) as $key => $value) {
            $key = $this->removeTableFromKey($key);
 
            // The developers may choose to place some attributes in the "fillable" array
            // which means only those attributes may be set through mass assignment to
            // the model, and all others will just get ignored for security reasons.
            if ($this->isFillable($key)) {
                $this->setAttribute($key, $value);
            } elseif ($totallyGuarded) {
                throw new MassAssignmentException(sprintf(
                    'Add [%s] to fillable property to allow mass assignment on [%s].',
                    $key, get_class($this)
                ));
            }
        }
 
        return $this;
    }

注释:使用 模型:create(数组)方法,传递数组赋值的,相应的模型中就必须有两个属性起作用分别是$guarded$guarded
解决方法:

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class 模型名称 extends Model
{
    protected $guarded;//不可以注入的数据字段
    protected $fillable = ['title','content',……];//可以注入的数据字段
}

这样就OK

阅读 60

Comments