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条)

报告相同问题?

悬赏问题

  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验