dongpenggan6812 2015-05-24 10:43
浏览 29
已采纳

从刀片中的laravel列表输出值

I have a laravel list defined in my controller as follows:

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

How do I output or access the columns in blade templating?

I do the following and I get error 'trying to get property of non object':

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

How can I iterate using a for loop as well as I'm trying to determine the first iteration - using the below i get offset error.

@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 

And how do I iterate the $salaries array - do i need to make it a collection since Salary::lists('id', 'range', 'rate'); array only contains two columns and strangely when i do 'dd($salaries);` why is the array defined with the 'range' value as the key and the 'id' as the value despite it being declared with 'id' being the key?

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

2条回答 默认 最新

  • dongyi1215 2015-05-24 11:51
    关注

    I'm afraid you understood lists() a bit wrong. First of all, it builds an array, and arrays have a key and a value. There's no room for a third attribute, and the lists() function therefore only takes two arguments:

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

    Also, the first argument is the value and the second one is the key. This is due to the fact that you can also build an array with numeric keys only.

    So you should do this instead:

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

    And then, in your foreach loop you don't have to treat it like an object, it's just the value:

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

    However, in your case I don't really see the benefit of using lists(). Just retrieve the full model collection with Industry::all() and you can do things like $industry->id and $industry->name and you will be able to handle more than just two values.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路