【问题标题】:Trying to get property of non-object Laravel 5.5试图获取非对象 Laravel 5.5 的属性
【发布时间】:2017-12-16 10:34:17
【问题描述】:

我试图在我的文章中呼应用户的名字,我得到了

ErrorException: Trying to get property of non-object.

我的代码:

报价模式

class Offer extends Model
{
    public function countries()
    {
        return $this->belongsTo(Country::class, 'country_id');    
    }
}

国家模式

class Country extends Model
{
    public function offers()
    {
        return $this->hasMany(Offer::class);
    }
}

index.blade

{{ $offer->countries->name }}

OfferController

public function index()
{
    $offers = Offer::latest()->paginate(5);
    return view('admin.offers.index', compact('offers'))

当 Idd($offer->first()->countries) 时结果为空。

【问题讨论】:

  • 试试 echo "
    "; print_r($offers);死;
  • 另外 $offer 不是一个正确的对象,你返回的是 $offers
  • 您可能需要更新您的刀片文件,例如 foreach @foreach($offers as $offer) {{ $offer->countries->name }} @endforeach 但首先检查您的 json 中的内容字符串。
  • “{{ $offer->countries->name }}”在 foreach 循环中插入 print_r($offers) 的位置?
  • 在foreach的顶部进行检查

标签: php laravel laravel-5 laravel-5.5


【解决方案1】:
class Offer extends Model
{
    // try change countries to country, because it's one to one relation.
    public function country()
    {
        return $this->belongsTo(Country::class);    
    }
}

然后在回显关系时使用可选

{{ optional($offer->country)->name }}

可选函数接受任何参数,并允许您访问该对象的属性或调用方法。如果给定对象为 null,属性和方法将简单地返回 null 而不会导致错误:

【讨论】:

  • 一般来说,如果答案包含对代码的用途的解释,以及为什么在不介绍其他人的情况下解决问题的原因,答案会更有帮助。
【解决方案2】:

您需要在刀片文件中添加 foreach 循环,如下所示:

@foreach($offers as $offer) 
{{ $offer->countries->name }} 
@endforeach    

【讨论】:

  • 它实际上嵌套在一个 foreach 循环中,就像你做的那样。
  • 可以在 $offers = Offer::latest()->paginate(5); 之后调试还有
  • 只需添加 echo "
    "; print_r($offers);死;在此之后
  • 你能告诉我你的表名吗?
  • 数据必须来自报价表。首先尝试简单的查询,例如 $offers = Offer::get();
猜你喜欢
  • 2018-06-06
  • 2018-07-03
  • 2018-03-03
  • 2018-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-24
  • 1970-01-01
相关资源
最近更新 更多