从刀片中的laravel列表输出值

ada*_*m78 0 php arrays for-loop blade laravel-5

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

$industries = Industry::lists('id', 'name');
$salaries = Salary::lists('id', 'range', 'rate');
Run Code Online (Sandbox Code Playgroud)

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

我做了以下操作,我收到错误'试图获取非对象的属性':

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

如何迭代使用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 
Run Code Online (Sandbox Code Playgroud)

我如何迭代$ salaries数组 - 我是否需要使它成为一个集合,因为Salary::lists('id', 'range', 'rate');数组只包含两列而奇怪的是当我做'dd($ salaries);`为什么数组定义为'range'值为key和'id'作为值,尽管它被声明为'id'是关键?

array:33 [
 "10,000 - 15,000" => 24
 "15,000 - 20,000" => 25
] 
Run Code Online (Sandbox Code Playgroud)

luk*_*ter 5

我怕你理解lists()有点不对劲.首先,它构建一个数组,数组有一个和一个.第三个属性没有空间,lists()因此该函数只有两个参数:

public function lists($column, $key = null)
Run Code Online (Sandbox Code Playgroud)

此外,第一个参数是,第二个参数是.这是因为您还可以仅使用数字键构建数组.

所以你应该这样做:

$industries = Industry::lists('name', 'id');
Run Code Online (Sandbox Code Playgroud)

然后,在你的foreach循环中,你不必像对象一样对待它,它只是值:

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

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