Laravel:尝试获取非对象的 属性,尽管 return 值是正确的
Laravel: Trying to get property of non-object although return value is right
已解决
当我到达一个在模板中调用方法的页面时出现此错误。
ErrorException in Product.php line 104:
Trying to get property of non-object (View: C:\wamp64\www\ibpc\resources\views\admin\products\edit.blade.php)
在 blade 模板中我调用了一个方法属性:
{{ $product->attribute($attribute->id) }}
模板中的 $product 从控制器传递为:
$product = Product::with('categories.specifications.attributes')->find($id);
Product.php中的方法属性:
public function attribute($id)
{
$attribute = $this->attributes()->find($id);
$test = $attribute->pivot->value;
return $test;
}
我用 xdebug 进行了调试,一切似乎都很好:
为什么会出错?
如果我这样做,我就不会出错:
public function attribute($id)
{
return 'Hello';
}
我必须检查空值...
public function attribute($id)
{
$attribute = $this->attributes()->find($id);
if ($attribute) {
$test = $attribute->pivot->value;
} else {
$test = null;
}
return $test;
}
已解决
当我到达一个在模板中调用方法的页面时出现此错误。
ErrorException in Product.php line 104:
Trying to get property of non-object (View: C:\wamp64\www\ibpc\resources\views\admin\products\edit.blade.php)
在 blade 模板中我调用了一个方法属性:
{{ $product->attribute($attribute->id) }}
模板中的 $product 从控制器传递为:
$product = Product::with('categories.specifications.attributes')->find($id);
Product.php中的方法属性:
public function attribute($id)
{
$attribute = $this->attributes()->find($id);
$test = $attribute->pivot->value;
return $test;
}
我用 xdebug 进行了调试,一切似乎都很好:
为什么会出错?
如果我这样做,我就不会出错:
public function attribute($id)
{
return 'Hello';
}
我必须检查空值...
public function attribute($id)
{
$attribute = $this->attributes()->find($id);
if ($attribute) {
$test = $attribute->pivot->value;
} else {
$test = null;
}
return $test;
}