【问题标题】:Laravel 5.2 injecting object into Blade templateLaravel 5.2 将对象注入 Blade 模板
【发布时间】:2016-04-17 05:45:00
【问题描述】:

我正在将一个员工模型绑定到一个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-&gt;country-&gt;name 在此输入中的正确语法是什么?

顺便说一句,这很有效,但是我这样做并没有学到任何东西!

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

【问题讨论】:

    标签: php laravel-5.2 laravelcollective


    【解决方案1】:

    我相信 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 有时就是这样)。我只是通过 trawling the source 找到它 - 虽然使用 PhpStormShamless Plug

      确实很容易

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

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

    3. 我把这个放在这里给以后遇到问题的人,但不推荐

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

    【讨论】:

      猜你喜欢
      • 2017-01-27
      • 2016-01-21
      • 1970-01-01
      • 2016-06-17
      • 2016-12-18
      • 2017-09-10
      • 2013-07-21
      • 2016-04-14
      • 2014-06-20
      相关资源
      最近更新 更多