Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: 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?

like image 442
thefalasifas Avatar asked Jun 18 '14 05:06

thefalasifas


3 Answers

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;
}
like image 104
alex t Avatar answered Nov 14 '22 13:11

alex t


Actually your $product has no data because the Eloquent model returns NULL. It's probably because you have used whereOwnerAndStatus which seems wrong and if there were data in $product then it would not work in your first example because get() returns a collection of multiple models but that is not the case. The second example throws error because foreach didn't get any data. So I think it should be something like this:

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

Further you may also make sure if $products has data:

if($product) {
    return View:make('viewname')->with('products', $products);
}

Then in the view:

foreach ($products as $product) {
    // If Product has sku (collection object, probably related models)
    foreach ($product->sku as $sku) {
        // Code Here        
    }
}
like image 44
The Alpha Avatar answered Nov 14 '22 11:11

The Alpha


The view (blade template): Inside the loop you can retrieve whatever column you looking for

 @foreach ($products as $product)
   {{$product->sku}}
 @endforeach
like image 24
Ghanshyam Nakiya Avatar answered Nov 14 '22 13:11

Ghanshyam Nakiya