非法字符串偏移量和试图获取非对象的属性(laravel 5.3)



所以我在刀片中打印数据来自控制器的结果时遇到了问题,所以:

  1. 使用控制器.php :

    $expertCategory = Category::getCategoryByID($user_id);
    $data = [ 'expertCategory' => $expertCategory ];
    return view('cms.user.edit', $data);
    
  2. Category
  3. .php (models( getCategoryByID($user_id( 返回结果数组,如果 i dd(expertCategory(; in 控制器,其结果为:

    array:9 [▼
    "id" => 1
    "name" => "Beauty"
    "sequence" => 1
    "background_color" => "ffffff"
    "status" => "Active"
    "created_at" => "2017-06-19 09:41:38"
    "updated_at" => "2017-06-19 09:41:38"
    "icon_filename" => "beauty-icon"
    "iconURL" => array:3 [▼
    "small" => "http://localhost:8000/images/category_icons/small/beauty-icon"
    "medium" => "http://localhost:8000/images/category_icons/medium/beauty-icon"
    ]
    ]
    
  4. 但是当我想在刀片中使用foreach打印结果时.php使用代码:

    @foreach($expertCategory as $expertCat)
    {{ $expertCat->id }}
    @endforeach
    

将返回错误"尝试获取非对象的属性">

如果我使用这样的代码:

@foreach($expertCategory as $expertCat) {{ $expertCat['id'] }} @endforeach

它将返回:"非法字符串偏移量'id'">

任何人都可以帮助解决这个问题:s? 非常感谢!

由于$expertCategory是一个dimensional array您面临此问题

只需替换此

$expertCategory = Category::getCategoryByID($user_id);
$data = [ 'expertCategory' => $expertCategory ];
return view('cms.user.edit', $data);

$expertCategory = Category::getCategoryByID($user_id);
$data = [ 'expertCategory' => [$expertCategory] ];
return view('cms.user.edit', $data);

然后使用

@foreach($expertCategory as $expertCat)
{{ $expertCat['id'] }}
@endforeach

在您的刀片中,它将为您工作。

最新更新