Laravel创建集合并在视图打印时触发非对象属性获取错误求助
解决Laravel中「Trying to get property of non-object」错误
问题根源
你碰到的这个错误,本质是集合结构和视图遍历逻辑不匹配导致的:
- 你用
Collection::make()直接把关联数组转成了集合,这时候集合的结构是「键为meta_title这类字段名,值为对应字符串」,而不是你预期的「包含单个SEO对象/数组的集合」。 - 视图里你遍历这个集合时,
$seo1其实是单个字符串(比如第一个循环拿到的就是meta_title对应的标题文本),你却试图用对象属性的方式(->)访问它的属性,自然会报错——字符串可不是对象。
修复方案
根据你的实际需求,有两种简单的修复方式:
方案一:直接用关联数组(推荐,因为是单条SEO数据)
如果只是单条SEO配置,完全没必要用集合,直接用关联数组更简洁:
// 后端控制器代码 $seo = [ "meta_title" => "Eco Elegant - Frp Dustbins & Planters Manufacturers in India", "meta_desc" => "Eco Elegant is the leading manufacturer and designers of stainless steel/ (Fiber Reinforced Plastic) FRP planters and dustbins for places with diverse usage needs.", "meta_keyword" => "Eco Elegant, Frp Dustbins, Frp Planters, Stainless Steel Dustbins, Stainless Steel Planter, Dustbins and Planter Suppliers, Exporters in India" ];
视图代码去掉多余的循环,直接访问数组元素:
@if(!empty($seo)) <title>{{ $seo['meta_title'] }}</title> <meta name="description" content="{{ $seo['meta_desc'] }}"> <meta name="keywords" content="{{ $seo['meta_keyword'] }}"> @else <title>Eco Elegant</title> <meta name="description" content=""> <meta name="keywords" content=""> @endif
方案二:如果确实需要使用集合(比如后续要扩展多条数据)
如果你坚持要用集合,需要把关联数组包装成集合的单个元素,这样遍历的时候才能拿到完整的SEO数据:
// 后端控制器代码:创建包含单个关联数组的集合 $seo = Collection::make([ [ "meta_title" => "Eco Elegant - Frp Dustbins & Planters Manufacturers in India", "meta_desc" => "Eco Elegant is the leading manufacturer and designers of stainless steel/ (Fiber Reinforced Plastic) FRP planters and dustbins for places with diverse usage needs.", "meta_keyword" => "Eco Elegant, Frp Dustbins, Frp Planters, Stainless Steel Dustbins, Stainless Steel Planter, Dustbins and Planter Suppliers, Exporters in India" ] ]);
视图里用数组方式访问元素:
@if($seo->count() > 0) @foreach($seo as $seo1) <title>{{ $seo1['meta_title'] }}</title> <meta name="description" content="{{ $seo1['meta_desc'] }}"> <meta name="keywords" content="{{ $seo1['meta_keyword'] }}"> @endforeach @else <title>Eco Elegant</title> <meta name="description" content=""> <meta name="keywords" content=""> @endif
要是想继续用对象属性访问(->),可以把数组转成对象:
$seo = Collection::make([ (object)[ "meta_title" => "Eco Elegant - Frp Dustbins & Planters Manufacturers in India", "meta_desc" => "Eco Elegant is the leading manufacturer and designers of stainless steel/ (Fiber Reinforced Plastic) FRP planters and dustbins for places with diverse usage needs.", "meta_keyword" => "Eco Elegant, Frp Dustbins, Frp Planters, Stainless Steel Dustbins, Stainless Steel Planter, Dustbins and Planter Suppliers, Exporters in India" ] ]);
内容的提问来源于stack exchange,提问作者Anil Kumar Sahu
相关产品推荐
相关产品推荐

