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?
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With