Laravel foreach loop in the controller

I have a problem with loop data in the controller (laravel 4). my code looks like this:

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

when I want to use foreach for a loop for the result of $ product with this code:

 foreach ($product->sku as $sku) { // Code Here } 

the result returns an error Undefined property: Illuminate \ Database \ Eloquent \ Collection :: $ sku

So, I'm trying to improvise a bit with this code:

 foreach ($product as $items) { foreach ($items->sku as $sku) { // Code Here } } 

error returning code, for example: Invalid argument for foreach ()

is there anyone who could help me with this?

+6
source share
3 answers

Hi, 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 a table.
Thus, you should go in cycles on all model:

 foreach ($product as $p) { // code } 

Inside the loop, you can get any column that you just want to add "-> [column_name]"

 foreach ($product as $p) { echo $p->sku; } 

Have a nice day

+20
source

Is sku just a property of the Product model? If yes:

 $products = Product::whereOwnerAndStatus($owner, 0)->take($count)->get(); foreach ($products as $product ) { // Access $product->sku here... } 

Or is sku related to another model? If so, then, as long as your relationship is set up correctly, your code should work.

0
source

In fact, your $product has no data, because the Eloquent model returns NULL. Probably because you used whereOwnerAndStatus , which seems to be wrong, and if there was data in $product , then this would not work in your first example, because get() returns a collection of several models, but that is not the case. The second example throws an error because foreach did not receive 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(); 

In addition, you can also verify that $products has data:

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

Then in view :

 foreach ($products as $product) { // If Product has sku (collection object, probably related models) foreach ($product->sku as $sku) { // Code Here } } 
0
source

Source: https://habr.com/ru/post/970982/


All Articles