在不可填写的字段上进行批量分配

时间:2014-01-17 08:30:13

标签: php laravel-4 eloquent mass-assignment

我正在为一个只有两个字段的简单模型编写一些单元测试:question_id和title。

我在模型上设置了可填充数组,只包含标题:

protected $fillable = array('title');

我还创建了以下单元测试:

    /**
     * @expectedException Illuminate\Database\Eloquent\MassAssignmentException
     */
    public function testAnswerQuestionIdCanNotBeMassAssigned()
    {
        $params = ['question_id' => 1, 'title' => 'something'];
        $answer = new Answer($params);
    }

但是,不会抛出任何异常,导致测试失败。

我在这里错过了什么吗?

任何建议表示赞赏。

感谢。

1 个答案:

答案 0 :(得分:2)

你可以在模型的填充方法中看到原因

public function fill(array $attributes)
{
    $totallyGuarded = $this->totallyGuarded();

    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 be ignored.
        if ($this->isFillable($key))
        {
            $this->setAttribute($key, $value);
        }
        elseif ($totallyGuarded)
        {
            throw new MassAssignmentException($key); <--- only if totally guarded
        }
    }

    return $this;
}