Laravel 5.0:Form :: select()通过选择名称调用两次Eloquent Accessor

时间:2015-06-17 10:40:05

标签: php laravel eloquent laravel-5 accessor

刀片模板:

{!! Form::model($category) !!}

    {!! Form::select('drinks_id', [...full list...]) !!}

{!! Form::close() !!}
Eloquent Accessor

调用

'drinks_id'

public function getDrinksIdAttribute()
{
    var_dump('get');
    return 123;
}

执行Form::select('drinks_id')时,getDrinksIdAttribute()调用两次并从string(3) "get" string(3) "get"打印var_dump()

如果我写这个:

{!! Form::model($category) !!}

    {!! var_dump($category->drinks_id) !!}

{!! Form::close() !!}

它曾拨打getDrinksIdAttribute()

这是Form::select()错误,或者我做错了什么?

1 个答案:

答案 0 :(得分:1)

FormBuilder使用object_get()辅助函数从模型中获取值:

/**
 * Get the model value that should be assigned to the field.
 *
 * @param  string  $name
 * @return string
 */
protected function getModelValueAttribute($name)
{
    if (is_object($this->model))
    {
        return object_get($this->model, $this->transformKey($name));
    }
    elseif (is_array($this->model))
    {
        return array_get($this->model, $this->transformKey($name));
    }
}

object_get()两次称为Eloquent Accessor:

object_get() helper function code

解决方案:

{!! Form::model($category) !!}

    {!! Form::select('drinks_id', [...full list...], $category->drinks_id) !!}

{!! Form::close() !!}