【问题标题】:Outputing values from a laravel list in blade从刀片中的 laravel 列表中输出值
【发布时间】:2015-08-06 00:07:38
【问题描述】:

我在控制器中定义了一个 laravel 列表,如下所示:

$industries = Industry::lists('id', 'name');
$salaries = Salary::lists('id', 'range', 'rate');

如何输出或访问刀片模板中的列?

我执行以下操作并收到错误“尝试获取非对象的属性”:

@foreach ($industries as $industry)
<div class="checkbox margin-top-0  ">
  <label>
    {!! Form::checkbox('industry_list[]', $industry->id) !!}
    {{$industry->name}}
  </label>
</div>
@endforeach

我如何使用 for 循环进行迭代以及我试图确定第一次迭代 - 使用下面我得到偏移错误。

@for ($i = 0; $i <= count($salaries); $i++)
<div class="checkbox @if($i == 0) margin-top-0 @endif ">
  <label>
    {!! Form::checkbox('salary_list[]', $salaries->id) !!}
    {{$salaries->name}}
  </label>
</div>
@endfor 

以及如何迭代 $salaries 数组 - 我是否需要将其设为一个集合,因为 Salary::lists('id', 'range', 'rate'); 数组仅包含两列,奇怪的是,当我执行 'dd($salaries);` 时,为什么数组是用“范围”值作为键,“id”作为值,尽管它被声明为“id”作为键?

array:33 [
 "10,000 - 15,000" => 24
 "15,000 - 20,000" => 25
] 

【问题讨论】:

    标签: php arrays for-loop laravel-5 blade


    【解决方案1】:

    恐怕您对lists() 的理解有点错误。首先,它构建一个数组,数组有一个key和一个value。第三个属性没有空间,因此lists() 函数只需要两个参数:

    public function lists($column, $key = null)
    

    另外,第一个参数是value,第二个参数是key。这是因为您也可以仅使用数字键构建数组。

    所以你应该这样做:

    $industries = Industry::lists('name', 'id');
    

    然后,在您的 foreach 循环中,您不必将其视为对象,它只是值:

    @foreach ($industries as $id => $industry)
        <div class="checkbox margin-top-0  ">
            <label>
                {!! Form::checkbox('industry_list[]', $id) !!}
                {{$industry}}
            </label>
        </div>
    @endforeach
    

    但是,在您的情况下,我并没有真正看到使用 lists() 的好处。只需使用Industry::all() 检索完整的模型集合,您就可以执行$industry-&gt;id$industry-&gt;name 之类的操作,您将能够处理两个以上的值。

    【讨论】:

      【解决方案2】:

      用途:

      $industries = Industry::all('id', 'name');
      $salaries = Salary::all('id', 'range', 'rate');
      

      静态集合|模型[] all(array $columns = array('*'))

      从数据库中获取所有模型。

      参数数组 $columns
      返回 值集合|模型[]

      参考:http://laravel.com/api/5.0/Illuminate/Database/Eloquent/Model.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-23
        • 1970-01-01
        • 2019-07-29
        • 2016-06-08
        • 1970-01-01
        • 2023-03-11
        • 2018-12-25
        相关资源
        最近更新 更多