laravel foreach loop in controller
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
}
}
The view (blade template): Inside the loop you can retrieve whatever column you looking for
@foreach ($products as $product)
{{$product->sku}}
@endforeach
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;
}