Laravel 5.2将对象注入到Blade模板中


Laravel 5.2 injecting object into Blade template

我正在将员工模型绑定到Blade模板中,并希望将热切加载关系的结果放入字段中。

在我的控制器中,我将页面的集合构建为:

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

我的公开声明是:

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

因此,我想将$employee->country->name填充到输入Laravel Collective form::text语句中,但我无法获得要加载的国家名称。表单上的所有其他字段完全从父集合加载。

我的国家字段是:

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

上面的country字段将整个关系结果加载到输入中。此输入中injecting $employee->country->name的正确语法是什么?

顺便说一句,这非常有效,但我通过这种方式什么都没学到!

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

我相信LaravelCollective中的FormBuilder使用data_get(Laravel辅助函数)从对象中获取属性。然而,元素名称中的点有点奇怪,所以我为您深入研究了一些来源。

您有以下选择之一(根据我的喜好订购):

  1. 您可以在Employee模型中添加一个名为getFormValue的方法。这需要一个参数,该参数是请求值的表单元素的名称。实现方式如下:

    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有时就是这样)。我只是通过搜索来源找到的-尽管使用PhpStormShamless Plug确实很容易

    这样做的缺点是,您会丢失转换,并尝试使用data_get从员工对象中提取值。

  2. 将文本字段的名称更改为country[country]。在源中,生成器将"["answers"]"替换为"。"在对象中查找属性时分别为"answers"。这意味着data_get将寻找country.country

  3. 我把这个放在这里是为了将来有这个问题的人,但不建议使用

    为您的员工模型提供getCountryAttribute方法。正如文档中"Form Model Accessors"标题下所解释的,您可以覆盖从$employee->country返回的内容。这意味着您无法访问真实对象。