无法在Laravel 5.4中将类型为stdClass的对象用作数组

时间:2018-11-15 18:11:12

标签: php laravel laravel-5.4

这是我的控制器功能

public function plist(){
    $plists = DB::table('panchayaths')->get(); 
    return view('webapp.panchayath list', ['plists' => $plists]);;       
}

这是我的观点

@foreach ($plists as $plist) 
<td> {{$plist['id']}}</td>
<td> {{$plist['pname']}}</td>
<td> {{$plist['total_ward']}}</td>
@endforeach

2 个答案:

答案 0 :(得分:0)

您是否尝试过$ plist-> id。 get响应是一个对象,而不是关联数组。.如果要在刀片中将其用作数组,请在get()之后添加-> toArray()。

答案 1 :(得分:0)

在控制器中:

public function plist()
{
    $plists = DB::table('panchayaths')->get()->toArray(); 
    return view('webapp.panchayath list', ['plists' => $plists]);
}

如果使用雄辩的ORM,则为:

public function plist()
{
    $plists = Panchayaths::all(); 
    return view('webapp.panchayath list', ['plists' => $plists]);
}

视图中:

@foreach ($plists as $plist) 
    <tr>
        <td> {{$plist['id']}}</td>
        <td> {{$plist['pname']}}</td>
        <td> {{$plist['total_ward']}}</td>
    </tr>
@endforeach

OR:

@foreach ($plists as $plist) 
    <tr>
        <td>{!! $plist->id !!}</td>
        <td>{!! $plist->pname !!}</td>
        <td>{!! $plist->total_ward !!}}</td>
    <tr>
@endforeach