i have a problem about looping data in controller (laravel 4). my code is like this:
JavaScript
x
$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:
JavaScript
foreach ($product->sku as $sku) {
// Code Here
}
the result is returning error Undefined property: IlluminateDatabaseEloquentCollection::$sku
so, i try to improvise a little with this code:
JavaScript
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?
Advertisement
Answer
This will throw an error:
JavaScript
foreach ($product->sku as $sku){
// Code Here
}
because you cannot loop a model with a specific column ($product->sku
) from the table.
So, you must loop on the whole model:
JavaScript
foreach ($product as $p) {
// code
}
Inside the loop you can retrieve whatever column you want just adding ->[column_name]
JavaScript
foreach ($product as $p) {
echo $p->sku;
}