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?
The view (blade template): Inside the loop you can retrieve whatever column you looking for
@foreach ($products as $product)
{{$product->sku}}
@endforeach
Is sku
just a property of the Product
model? If so:
$products = Product::whereOwnerAndStatus($owner, 0)->take($count)->get();
foreach ($products as $product ) {
// Access $product->sku here...
}
Or is sku
a relationship to another model? If that is the case, then, as long as your relationship is setup properly, you code should work.
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
}
}
Source: Stackoverflow.com