Skip to content
Advertisement

laravel foreach loop in controller

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
}

the result is returning error Undefined property: IlluminateDatabaseEloquentCollection::$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?

Advertisement

Answer

This will throw an error:

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:

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;
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement