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>

以上国家/地区字段将整个关系结果加载到输入中。此输入中 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 辅助函数)从 object 中获取属性。但是,元素名称中的点有点奇怪,所以我为您深入研究了源代码。

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

  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 就是这样)。我只是通过 trawling the source 找到它的——尽管使用 PhpStormShamless Plug 确实很容易

    这样做的缺点是您失去了转换并试图从您的员工 object 和 data_get 中提取价值。

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

  3. 为了以后有问题的人放这里,不推荐.

    为您的员工模型提供一个 getCountryAttribute 方法。如 the documentation 中 "Form Model Accessors" 标题下所述,您可以覆盖从 $employee->country 返回的内容。这意味着您无法访问真正的 object。