laravel foreach loop in controller - php

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

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.

$allData = Model::where('status', 1)->get();
foreach ($allData as $data){
$data->status = 0;
$data->update();
}
Here every $data is single data and $allData contains full collection.

using foreach on table
for me
#foreach($products as $data)
<tr>
<td>{{$data->id}}</td>
<td>{{$data->name}}</td>
<td>{{$data->price}}</td>
</tr>
#endforeach

Edit multiple data in laravel
You can use this for updating multiple data in laravel, which i have tested it and it works for me.
also remember i used relatationship here

Related

How to send relational data from multiple foreach to view in Laravel

I made a Laravel project where Category, Subcategory and Child category working using same table relation.
I want to show all products from childcategory when click to Main Category.
So for that I need to use multiple foreach loop like this,
foreach ($categories->subcategories as $subcat)
{
foreach ($subcat->childcategories as $childcat )
{
$products = $childcat->products;
}
}
Now I want to send $products to a view. How can I do it.
I don't want to use array. How can I send It. Please help.
Use Array()
$products = array()
foreach ($categories->subcategories as $subcat)
{
foreach ($subcat->childcategories as $childcat )
{
$products[] = $childcat->products;
}
}
return view(....);
In Laravel you can pass your Category Object to the view. In Blade you have access to the relationships of Category. You can testet by :
dd($categories->subcategories) or dd($categories->subcategories[]->childcat).

How to iterate a foreach loop starting from the last element in php?

I have a resultset fetched from database in laravel through this code.
$products = Product::whereNull('box_size')->get();
There are about 18000 objects in $products variable. I need to get the previous object of the last object from the list. How can I do so? Is there any way to iterate through a foreach loop from the last of a resultset?
If you only need that one record, be more precise in your query to avoid a lot of extra data loading and processing:
$products = Product::whereNull('box_size')
->orderBy('created_at', 'DESC')
->skip(1)
->take(1)
->get();
You can do it from your model easily (for last 10 query) :
$products = Product::orderBy('id', DESC)->whereNull('box_size')->take(10)->get();
For just last query :
$products = Product::orderBy('id', DESC)->whereNull('box_size')->first();
Or, With foreach loop get only 10 result :
#php
$i= 0;
#endphp
#foreach($all as $data) {
$i++;
include $data->name;
if($i == 10) break;
}
#endforeach
A mentioned above you can do so through your model:
$products = Product::latest()->whereNull('box_size')->get();
This will give you eloquent for all products sorted by DESC in column created_at.
You can sort the results with descend order, and then the second item is what you want:
$products = Product::orderBy('id', DESC)->whereNull('box_size')->get();
$item = $products[1];
Directly access the item from the Collection object:
$products = Product::whereNull('box_size')->get();
$item = $products->get($products->count() - 2);
//or pop
$products->pop()
$item = $products->pop();

Magento's getItemsCollection is not applying filters

I'm trying to apply filter to the quote items collection, i get the collection using this
$items_collection = Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection();
$items_collection->addFieldToFilter('product_id', $_product->getId());
when i print out the select query, the query is correct
$items_collection->getSelect()
But when i iterate through the collection, it is fetching all of the items, it did not apply the filter, does anyone know why?
foreach ($items_collection as $item) {
// Do things....
}
Try this. Use getModel instead of getSingleton.
$items_collection = Mage::getModel('checkout/session')->getQuote()->getItemsCollection();
$items_collection->addFieldToFilter('product_id', $_product->getId());
foreach ($items_collection as $item) {
echo $item->getProduct()->getId();
}

Use variable outside foreach laravel

I have a problem with Laravel. So what am I trying to do? I'm trying to get the location from all my examples. This actually works, so as you can see I get the id of all the examples and find the locations of it from another table in my project. The var_dump in the foreach gives what I need. But I need this data outside the foreach, I need to send it to my view afterwards. But the second var_dump, the one outside the foreach only gives the location of the first id.
So my question: is there a way to get the full $locations outside the foreach.
$ids= DB::table('example')
->select('id')
->get();
foreach($ids as $id)
{
$locations = example::find($id->id)->locations()->get();
var_dump($locations);
}
var_dump($locations);
This is my view:
#foreach($examples as $example)
<h1>{{$example->name}}</h1>
#foreach($locations as $location)
{{$location}}
#endforeach
#endforeach
I see al the locations from al the $examples in every $example if I print it like this, I hope you understand my question.
Try this:
// Define locations array
$locations = [];
// Then do the following for each example:
// Define the array for locations of each example outside of the loop
$locations[$example->name] = [];
foreach ($ids as $id) {
// Add each location to the $locations array
$locations[$example->name][] = example::find($id->id)->locations()->get();
}
Or if you want to get a little bit more fancy, you can use array_map instead of foreach:
$locations[$example->name] = array_map(function ($id) {
return example::find($id->id)->locations()->get();
}, $ids);
Then in the view, you simply take out the locations from the right key for each example:
#foreach ($examples as $example)
<h1>{{ $example->name }}</h1>
#foreach ($locations[$example->name] as $location)
{{ $location }}
#endforeach
#endforeach
You don't have to use the $example->name as the key, just make sure it's unique for each example you want to fetch locations for.
I hope this helps.
There is no need to build the $locations array. You can use the relationship in the view just fine.
In your controller:
// whatever your logic is to get the examples
$examples = example::with('locations')->get();
In your view:
#foreach($examples as $example)
<h1>{{$example->name}}</h1>
#foreach($example->locations as $location)
{{$location}}
#endforeach
#endforeach

How to use a for loop on a collection pulled from Magento

im trying to use a for loop on products i pulled from Magento.
And it crashes when i want to use the index on a product in the loop.
$collection = Mage::getModel('catalog/product')->getCollection();
$collectionLength = count($collection);
for($j = 0; $j < $collectionLength; $j++)
{
$productFromStore = $collection[$j];//it crashes on this line of code
$sku = $productFromStore->getSku();
}
but when i use a foreach loop i can reach all the products.
foreach($collection as $product)
{
// this code works fine
$sku = $product->getSku();
}
Can someone explain what is going wrong and why?
Thanks.
First of all, You trying to iterate collection object as array
Here is Error :
Fatal error: Cannot use object of type
Mage_Catalog_Model_Resource_Product_Collection as array
, second for loop isn't the best way to iterate collections better is foreach loop becacuse for loop need to count of array emelents foreach dont need it.
Third, the best way is to use magento resource iterator.
Mage::getSingleton('core/resource_iterator')
->walk(
$query->getSelect(),
array(array($this,'callbackFunction')));
here is an example:
public function someGetCollectionMethod()
{
$products = Mage::getModel('catalog/product')->getCollection();
Mage::getSingleton('core/resource_iterator')
->walk(
$products->getSelect(),
array(array($this, 'productsCallback')));
}
public function productsCallback($args)
{
$product = Mage::getModel('catalog/product');
$prod = $product->load($args['row']['entity_id']);
Zend_Debug::dump($prod->getSku());
}
Happy coding,
Adam
Collection classes in Magento's ORM ultimately subclass Varien_Data_Collection which implements IteratorAggregate; this is why you are able to work with the collection object in an array-like fashion (i.e. foreach), but not have it work for the for loop. For one thing, dThere is no direct key-based access to the elements inside the object (_items array members) - unfortunate, given that the key for the _items array is based on the row ID.
Bottom line: working with collection items in a for loop is not very easy, not when compared to the ease of working with collection items via IteratorAggregate and all of its related goodies.
Here's an example of both. If you have an overarching need to work with the collection's items directly then you can use $collection->getItems(), but again realize that the _items array keys may not be sequential as they are based on the data. Also, note that you need to add the name attribute value to collections stored using Magento's EAV pattern:
<?php
header('Content-Type: text/plain');
include('app/Mage.php');
Mage::app();
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addAttributeToSelect('name');
//for loop - not as much fun
for ($j=0;$j<count($collection);$j++) { //count() triggers $collection->load()
$items = $collection->getItems();
$item = current($items);
echo sprintf(
"%d:\t%s\t%s\n",
$k,
$item->getSku(),
$item->getName()
);
next($items); //advance pointer
}
//foreach - a bit better
foreach ($collection as $k => $product) {
echo sprintf(
"%d:\t%s\t%s\n",
$k,
$product->getSku(),
$product->getName()
);
}
And just in case you are wondering: Performance of FOR vs FOREACH in PHP
$array = array(
"foo" => "bar",
"bar" => "foo",
);
This type of array cannot be accessed by indexes you have to use,
$array["foo"];
If the keys are unpredictable you have to use
`foreach
I'm no expert in magento, but perhaps it's because the collection has different keys other than just numbers? Try printing out the collection with print_r to see what keys does the object have.
If you need iterations with numbers, you can always do something like that:
$i=0;
foreach($collection as $product)
{
$sku = $product->getSku();
$i++;
}
EDIT: Anyway, it seems collections aren't regular arrays, so you cannot use them the way you tried.
That's because you are sending an empty value to the getSku function.
<?php
$collection=array("book1"=>"bat","book2"=>"cat");
$collectionLength = count($collection);
for($j = 0; $j < $collectionLength; $j++)
{
$productFromStore = $collection[$j];
echo $productFromStore; //prints nothing !
}
foreach($collection as $var)
{
echo $var; //prints batcat
}
In magento collection return in form of object. use below code fetch SKU and NAME. Or use print_r($collection->getData()) to get data in array Key=>value format.
foreach($collection as $productCollection){
$sku = $productCollection->getSku();
$name = $productCollection->getName();
}

Categories