i have a problem about looping data in controller (laravel 4). my code is like this:

$owner = Input::get('owner');
$count = Input::get('count');
$product = Product::whereOwnerAndStatus($owner, 0)->take($count)->get();

when i want to use foreach to loop for $product result with code like this:

foreach ($product->sku as $sku) {
    // Code Here
}

结果返回错误 Undefined property: Illuminate\Database\Eloquent\Collection::$sku

so, i try to improvise a little with this code:

foreach ($product as $items) {
    foreach ($items->sku as $sku) {
        // Code Here        
    }
}

the code returning error like this: Invalid argument supplied for foreach()

is there someone who could help me solve this?

推荐答案

这将抛出一个错误:

foreach ($product->sku as $sku){ 
// Code Here
}

因为不能使用表中的特定列($product->sku)循环模型.

foreach ($product as $p) {
// code
}

Inside the loop you can retrieve whatever column you want just adding ->[column_name]

foreach ($product as $p) {
echo $p->sku;
}

Laravel相关问答推荐

如何使中继器项目计数动态Laravel Filament V3?

Laravel中的策略对我不起作用,这是我的代码

assertSee 由于 html 代码中的空格而失败

Laravel Debugbar 中的 Laravel api routes路由

Laravel 在维护模式下显示自定义消息

安卓 retrofit |发布自定义对象(将 json 发送到服务器)

如何从 laravel 控制器执行外部 shell 命令?

用 laravel 表单确认删除?

SQLSTATE [HY000]:一般错误:1005 无法创建表 - Laravel 4

Laravel lockforupdate(悲观锁)

Laravel 控制器构造

为什么客户凭证应该与 Laravel Passport 中的用户相关联?

如何更改默认 Laravel Auth 登录视图

使用 Laravel 将两个模型合并到一个分页查询中,并带有Eager加载的关系

Laravel Eloquent 查询生成器默认 Where 条件

assets资源不引用公用文件夹(Laravel)

如何在 Laravel 测试中禁用选定的中间件

Laravel 5 new auth:获取当前用户以及如何实现角色?

php artisan migrate - SQLSTATE [HY000] [1045] 用户'laravel'@'localhost'的访问被拒绝

如何访问 Laravel 集合中的第 n 个项目?