duanang58939 2017-07-30 13:29
浏览 51
已采纳

Laravel Pluck - 试图获得非对象的属性

I need to select the id and name field, pass the collection to the view and iterate over it to generate options for a select. However, I am getting the following error:

Trying to get property of non-object (View: ../resources/views/layouts/app.blade.php) (View: ../resources/views/layouts/app.blade.php)

Controller

public function index()
{
    $propertyTypes = PropertyType::pluck('name', 'id');
    return view('home', compact('propertyTypes'));
}

View

@foreach($propertyTypes as $propertyType)
    <option value="{{ $propertyType->id }}">
        {{ $propertyType->name }}
    </option>
@endforeach

Table

ID  Name
1   Detached
2   Semi-detached
3   Terraced
4   Flat
5   Bungalow
6   Land
7   Park Home
  • 写回答

4条回答 默认 最新

  • douyu0845 2017-07-30 13:39
    关注

    You're using the pluck method to get the results as key-value pair but in your view you're trying to access the value as an object which is causing this error.

    Either you've to fetch your results as models or you've to update your view.

    Option 1: Fetch results as models

    public function index()
    {
        $propertyTypes = PropertyType::select('name', 'id')->get();
        return view('home', compact('propertyTypes'));
    }
    

    Option 2: Iterate over collection as key-value

    @foreach($propertyTypes as $id => $name)
        <option value="{{ $id }}">
            {{ $name }}
        </option>
    @endforeach
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改