Getting a particular data from instance - laravel

I am trying to make a shopping cart in Laravel, and I am still a learner.
In the cart, I am trying to print details of products present in the cart, along with their quantity.
The details of several products of cart is present in $prod, while quantity is present in $cart. I am running a foreach to access each product of the cart, as well as its quantity.
In an explanatory way, I am trying to do this:
#foreach( $prod as $p )
<td>Quantity = {{ $cart[ "product_id" == $p->id]->quantity }}<td>
#endforeach
I am trying to match the $p->id, the details which I am printing, to the quantity in $cart as $cart has it under product_id attribute in table.
I am sorry if I am unable to explain the question the right way.
Thank you.

This solutions assumes you are using Eloquent Models, if you are not you should. On your Product.php model, define the relationship.
class Product extends Model {
public function cart()
{
// Laravel automatically know to look in carts table for an product_id column
return $this->belongsTo(Cart::class);
}
}
Now you have a relationship method for your cart, this is useful if you want to save it. For just loading it out of the database, if you access $product->cart it will automatically fetch the Cart.php model. So you can quite simply write.
#foreach( $prod as $p )
<td>Quantity = {{ $p->cart->quantity }}<td>
#endforeach

Related

How to get data from additional table in many to many relationship?

I have a many to many relationship between tables 'products' and 'recipes'. I created table product_recipe to handle this and my table looks like:
id | recipe_id | product_id | amount
In my blade file I use
#foreach($recipe->product as $row)
<p>{{ $row->name }}</p>
#endforeach
to get a name of used products in recipe. How I can get an amount of product which is stored in product_recipe table? Do I have to create a model for product_recipe table and get it from model?
You will have to declare the relationship wants to include the extra pivot information so that the pivot object that is attached to the records will have more than just the 'id's:
public function products()
{
return $this->belongsToMany(Product::class)->withPivot('amount');
}
Now the pivot object will include the field amount:
foreach ($recipe->products as $product) {
echo $product->pivot->amount;
}
"By default, only the model keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship"
Laravel 6.x Docs - Eloquent Relationships - Many To Many - Retrieving Intermediate Table Columns withPivot
You have to use pivot attribute.
#foreach($recipe->product as $row)
<p>{{ $row->pivot->field_name}}</p>
#endforeach
No need to create Model for product_recipe. Just specify table name in relation of two Models.
Like return $this->belongsToMany('App\Product', 'product_recipe')->withPivot('amount'); and similar for other model.

Laravel eloquent how to display data from 2 table

I have 2 tables, product and promotion. I do not know how I can display the price of both product and promotion(price after discount) based on product_id in blade. In blade i can only display price for promotion using {{$promotion->price}}
Product Table
id - name - price
Promotion Table
id product_id - price - discount
Controller:
$latestProduct = Promotion::orderBy('created_at', 'desc')
->with('product')
->take(20)
->get();
Model:
Product Model
public function promotion()
{
return $this->hasMany('App\Model\Promotion');
}
Promotion Model
public function product()
{
return $this->belongsTo('App\Model\Product');
}
in blade file:
Edit:
#foreach($latestProduct as $product)
{{$product->price}}
{{$product->promotion->price}}
#endforeach
would work.
I think it'll be better to make like this:
$latestProducts = Product::orderBy('created_at', 'desc')
->with('promotion')
->take(20)
->get();
And, as mentioned Ali Özen, in your blade file you'll be able to iterate through your products and get product's promotion price with:
$product->promotion->price

Laravel Output 1 result from hasmany relationship

I have a hasmany relationship on my model and I'm trying to output just the one result, i have a product category which can display only one product image.
I have two tables.
1 = Product
2 = ProductPhotos
I've tried outputting the one photo like
#foreach($products as $product)
<img src="{{ $product->photos->first() }}">
#endforeach
I have the following relationship setup in my product model
public function photos()
{
return $this->hasMany('App\ProductPhoto', 'product_id');
}
but this doesnt work.
You're just missing the parenthesis for the method. It should be:
$product->photos()->first();
Which will allow Eloquent to access the photos method in the Product model.

Magento - assign multiple product ids to a category

I have a category "new" that I want to assign to, via a daily cron, the most recent 120 products.
I am trying to override the product ids assigned to a category.
Is there an easy way , like :
$category->setProductIds(array())
In PHP code you can put them into the category while you are importing them.
Say you have a product called $product and a category ID called $category_id
You can set the categories which a product belongs to by doing the following
$categories = array($category_id);
$product->setCategoryIds($categories);
$product->save();
f the product already has categories and you'd like to add one more then you can use getCategoryIds() like this:
$categories = $product->getCategoryIds();
$categories[] = $categoryId;
$product->setCategoryIds($categories);
$product->save();
it works like this
$category = Mage::getModel('catalog/category')->load($categoryID);
$product_array = $category->getProductsPosition()
... make changes ... format : $item[$product_id] => $position_in_category
$category->setPostedProducts($product_array);
$category->save();
To Remove product from category:
Mage::getSingleton('catalog/category_api')->removeProduct($category->getId(),$p‌​roduct->getId());
To Add Product to Category:
Mage::getSingleton('catalog/category_api')->assignProduct($category->getId(),$p‌​roduct->getId());
Now you can loop through all products and assign those to category using category id.
Note: This will not overwrite any categories the product is already in.

How to get grouped product ID from purchased or cart product

I'm using grouped products to track promotions. Simple products will at times belong to multiple grouped products, so checking parentProductIds is of no use. I'm wondering how to track the grouped product ID when a product is purchased through the grouped (promotion) SKU. I can see it's being stored in info_buyRequest and super_product_config within the orders, but how do I get that information back out? And is there a way to get it out in the cart/quote?
I was able to get it with the following code in cart.phtml, in the foreach($this->getItems() as $_item):
$values = unserialize($_item->getOptionByCode('info_buyRequest')->getValue());
$parentId = $values['super_product_config']['product_id'];
Depending on where you want to get this information, you could get it after a checkout process when the sales is saved. Then you could use the events sales_order_save_after and create a method in a class to get the items of a grouped product.
What is important here is the object of a class Mage_Sales_Model_Order_Item which has information about the product and the parents of a product
Here is an example:
public function processSalesOrder($observer)
{
$order = $observer->getOrder()
$quoteItems = $order->getItemsCollection(null, true);
/*#var $item Mage_Sales_Model_Order_Item */
foreach ($quoteItems as $item) {
$parent = $item->getParentItem();
if(!is_null($parent)){
// do your stuff - you have a product parent which has children product
// $item is the children
echo 'The parent product is ' . $parent->getSku();
echo 'One of the children product is' .$item->getSku();
}
}
On cart page grouped product is treated as a simple product. In Magento 2 you can get the parent id of these simple products from session. This worked for me:
<?php
$catalogSession = $_SESSION['catalog'];
$parentId = $catalogSession['last_viewed_product_id'];
?>

Resources