从刀片中的laravel列表输出值

时间:2015-05-24 10:43:18

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

我在控制器中定义了一个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);`为什么定义了数组使用'range'值作为键,'id'作为值,尽管它被声明为'id'是关键?

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

2 个答案:

答案 0 :(得分:5)

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

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

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

所以你应该这样做:

$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->id$industry->name之类的操作,并且您将能够处理的不仅仅是两个值。

答案 1 :(得分:0)

使用:

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

static Collection | Model [] all(array $ columns = array('*'))

     

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

     

参数array $ columns
  返回   价值收集|模型[]

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