0

I am binding an employee model into a Blade template, and want to place the result of an eager load relation into a field.

In my controller I build the collection for the page as:

$employee = User::with('country', 'activeOrganisationRole')->first();

My form open statement is:

{!! Form::model($employee, ['route' => ['employee.role', $employee->uuid], 'method' => 'POST']) !!}

So I want to populate $employee->country->name into an input Laravel Collective form::text statement, but I cannot get the country name to load. All other fields on the form load perfectly from the parent collection.

My Country field is:

<div class="form-group">
    <label for="phone" class="control-label">Country</label>
    {!! Form::text('country', null, ['id'=>'country', 'placeholder' => 'Country', 'class' => 'form-control']) !!}
</div>

The above country field loads the entire relation result into the input. What is the correct syntax for injecting $employee->country->name into this input?

By the way , this works perfectly, but I have learned nothing by doing this way!

<label for="title" class="control-label">Country</label>
<input id="country" class="form-control" value="{!! $employee->country->country !!}" readonly>
4

1 回答 1

1

我相信FormBuilderLaravelCollective 使用data_get(Laravel 辅助函数)从对象中获取属性。但是,元素名称中的点有点奇怪,所以我为您深入研究了源代码。

您有以下选择之一(按我的喜好排序):

  1. getFormValue您可以添加在 Employee 模型中调用的方法。这需要一个参数,它是请求值的表单元素的名称。像这样实现它:

    public function getFormValue($name)
    {
        if(empty($name)) {
            return null;
        }
    
        switch ($name) {
            case 'country':
                return $this->country->country;
        }
    
        // May want some other logic here:
        return $this->getAttribute($name);
    }
    

    我真的找不到任何关于此的文档(Laravel 有时就是这样)。我只是通过搜索源代码才找到它-尽管使用 PhpStorm Shamless Plug确实很容易

    这样做的缺点是您会丢失转换并尝试使用data_get.

  2. 将文本字段的名称更改为country[country]. 在源代码中,构建器将 '[' 和 ']' 替换为 '.' 和 '' 分别在对象中查找属性时。这意味着data_get将寻找country.country.

  3. 我把这个放在这里给将来有问题的人,但不推荐

    给你的员工模型一个getCountryAttribute方法。如文档中“表单模型访问器”标题下所述,您可以覆盖从 $employee->country 返回的内容。这意味着您无法访问真实对象。

于 2016-04-17T08:26:28.863 回答