Access the cart session - Laravel 5.8 - laravel

Hi i am using sopping cart in laravel 5.8. I want to access the array to be able to store the order in the database. I was able to access the data in the session cart. But to the part of options -> marca y medida. Also I do not know how to bring the total cart.
My controller is as follows
public function transferencia(Request $request)
{
$cart = Session::get('cart');
foreach ($cart as $key => $order) {
$data = json_decode($order, true);
foreach($data as $item){
$opt = new Order;
$opt->id_cliente = $request->input('idusuario');
$opt->fecha = date('j/n/Y');
$opt->cliente = $request->input('persona');
$opt->dni = $request->input('dni');
$opt->producto = $item['name'];
$opt->medida = 'medida'; //how to access this data
$opt->marca = $item['marca']; //how to access this data
$opt->precio = $item['price'];
$opt->cantidad = $item['qty'];
$opt->total = 'total';
$opt->factura = 'factura';
$opt->idpedido = 'idpedido';
$opt->save();
}
}
//dd($item);
//print_r($cont);
}

Related

Laravel session

I have done projects laravel shopping cart when clicking on the product detail page will open and click the add to cart sends the id to CartController # index. I then access the database and retrieve product information and I put on the session. Then I bought other products but my older products lost in session when I turn the page. Who can help me thanks
Probably you don't add this to existed array in session, but replace it.
Should do it this way:
$products = Session::get('products', array()); // get existed products or empty array
$products[] = $newProduct; // add new product to list
Session::put('products', $products); // put all products to session
this is my code for cart
public function addItem($ids,Request $request){
$data = Product::find($ids)->toArray();
$name =$data['name'];
$price = $data['price'];
$cart = $request->session()->get('cart');
if($cart==null){
$cart['quantity'][$ids] = 1;
$cart['price'][$ids] = $price;
$cart['name'][$ids] = $name;
$request->session()->put('cart', $cart);
}else{
if(array_key_exists($ids,$cart['quantity'])){
$cart['quantity'][$ids] += 1;
$cart['price'][$ids] = $price * $cart['quantity'][$ids];
$cart['name'][$ids] = $name;
}else{
$cart['quantity'][$ids] = 1;
$cart['price'][$ids] = $price;
$cart['name'][$ids] = $name;
}
$request->session()->put('cart', $cart);
}
}

How to get Product listing filters through custom module of magento?

I want to create product filters in listing pages of category using our own custom apis i have tried many things like
$layer = Mage::getModel("catalog/layer");
$category = Mage::getModel("catalog/category")->load($categoryid);
$layer->setCurrentCategory($category);
$attributes = $layer->getFilterableAttributes();
But this only loads the Filterable atrribute code for the category But we want the Filters values and count for the product collection available in that category.
Below code will load all the available options of that attribute but I want it for product collection specific
foreach($attributes as $attribute){
$options = $attribute->getSource()->getAllOptions(false);
}
Like we have Mobiles category having 1000s of mobiles and having filterable attribute Brand so i need
Brand
Brand A (100 products)
Brand B (500 products)
Brand C (400 products)
How can this be achived if i don't want to load whole product collection as loading 1000s of product will take too much time to response.
This code works for me :
public function ws_getfiter($store_id,$categoryid){
Mage::app()->setCurrentStore($store_id);
$layer = Mage::getModel("catalog/layer");
$category = Mage::getModel("catalog/category")->load($categoryid);
$layer->setCurrentCategory($category);
$attributes = $layer->getFilterableAttributes();
$filter = array();
$count = 0;
foreach ($attributes as $attribute)
{
if ($attribute->getAttributeCode() == 'price') {
$filterBlockName = 'catalog/layer_filter_price';
} elseif ($attribute->getBackendType() == 'decimal') {
$filterBlockName = 'catalog/layer_filter_decimal';
} else {
$filterBlockName = 'catalog/layer_filter_attribute';
}
$filter[$count]["code"] = $attribute->attribute_code;
$filter[$count]["type"] = $attribute->frontend_input;
$filter[$count]["label"] = $attribute->frontend_label;
$result = Mage::app()->getLayout()->createBlock($filterBlockName)->setLayer($layer)->setAttributeModel($attribute)->init();
$innercount = 0;
$filter_data = array();
foreach($result->getItems() as $option) {
$filter_data[$innercount]["count"] = $option->getCount();
$filter_data[$innercount]["label"] = $option->getLabel();
$filter_data[$innercount]["id"] = $option->getValue();
$innercount++;
}
$filter[$count]["values"] = $filter_data;
$count++;
}
return $filter;
}
But using this we are only getting single level of filter but i want it for multiple level.

How to insert values in another table in controller joomla

I am using joomla 3.1.1 and joomshopping. i need to insert values in another table at same time when user register on website. In user controller i need to insert values in my custom table. can i use a direct insert query in my controller file. this is function in controller file to register user. Where i can put my code to insert data in another table.
function registersave(){
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
$mainframe = JFactory::getApplication();
$jshopConfig = JSFactory::getConfig();
$config = JFactory::getConfig();
$db = JFactory::getDBO();
$params = JComponentHelper::getParams('com_users');
$lang = JFactory::getLanguage();
$lang->load('com_users');
$post = JRequest::get('post');
JPluginHelper::importPlugin('captcha');
$dispatcher = JDispatcher::getInstance();
$res = $dispatcher->trigger('onCheckAnswer',$post['recaptcha_response_field']);
if(!$res[0]){
JError::raiseWarning('','Invalid Captcha');
$this->setRedirect("index.php?option=com_jshopping&controller=user&task=register",'','',$jshopConfig->use_ssl);
}
else
{
JPluginHelper::importPlugin('jshoppingcheckout');
$dispatcher = JDispatcher::getInstance();
if ($params->get('allowUserRegistration')==0){
JError::raiseError( 403, JText::_('Access Forbidden'));
return;
}
$usergroup = JTable::getInstance('usergroup', 'jshop');
$default_usergroup = $usergroup->getDefaultUsergroup();
if (!$_POST["id"]){
}
$post['username'] = $post['u_name'];
$post['password2'] = $post['password_2'];
//$post['name'] = $post['f_name'].' '.$post['l_name'];
$post['mailing_list'] = $post['mailing_list'];
$hear = '';
$post['where_did_you_purchase'] = $post['where_did_you_purchase'];
$post['ages_of_your_children'] = $agesofchilderen;
$post['comments_or_suggestions'] = $post['comments_or_suggestions'];
$post['vehicle_2'] = $post['vehicle_2_model'].'-'.$post['vehicle_2_year'];
if ($post['birthday']) $post['birthday'] = getJsDateDB($post['birthday'], $jshopConfig->field_birthday_format);
$dispatcher->trigger('onBeforeRegister', array(&$post, &$default_usergroup));
$row = JTable::getInstance('userShop', 'jshop');
$row->bind($post);
$row->usergroup_id = $default_usergroup;
$row->password = $post['password'];
$row->password2 = $post['password2'];
if (!$row->check("register")){
JError::raiseWarning('', $row->getError());
$this->setRedirect(SEFLink("index.php?option=com_jshopping&controller=user&task=register",1,1, $jshopConfig->use_ssl));
return 0;
}
$user = new JUser;
$data = array();
$data['groups'][] = $params->get('new_usertype', 2);
$data['email'] = JRequest::getVar("email");
$data['password'] = JRequest::getVar("password");
$data['password2'] = JRequest::getVar("password_2");
//$data['name'] = $post['f_name'].' '.$post['l_name'];
$data['username'] = JRequest::getVar("u_name");
$useractivation = $params->get('useractivation');
$sendpassword = $params->get('sendpassword', 1);
if (($useractivation == 1) || ($useractivation == 2)) {
jimport('joomla.user.helper');
$data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword());
$data['block'] = 1;
}
//echo $row->getTableName();
//print_r($row);
//die("kkk");
$user->bind($data);
$user->save();
$row->user_id = $user->id;
unset($row->password);
unset($row->password2);
if (!$db->insertObject($row->getTableName(), $row, $row->getKeyName())){
JError::raiseWarning('', "Error insert in table ".$row->getTableName());
$this->setRedirect(SEFLink("index.php?option=com_jshopping&controller=user&task=register",1,1,$jshopConfig->use_ssl));
return 0;
}
}
}
Try this,
Please do not edit Joomla core files.
If you need to add register data on your custom table the create a User Plugin.
Joomla provides lot of plugin events in your case you can use onUserAfterSave. event
Create a User plugin with onUserAfterSave event then simply use the Joomla DB library to your custom table entries.
Hope it helps..

CakePHP serializing objects

I'm stuck with the following problem:
I have a class CartItem. I want to store array of objects of CartItem in session (actually i'm implementing a shopping cart).
class CartItem extends AppModel{
var $name = "CartItem";
var $useTable = false;
}
I tried this:
function addToCart(){
$this->loadModel("Cart");
$this->layout = false;
$this->render(false);
$cart = array();
$tempcart = unserialize($this->Session->read("cart"));
if(isset($tempcart)){
$cart = $tempcart;
}
$productId = $this->request->data("id");
if(!$this->existsInCart($cart, $productId)){
$cartItem = new Cart();
$cartItem->productId = $productId;
$cartItem->createdAt = date();
$cart[] = $cartItem;
$this->Session->write("cart", serialize($cart));
echo "added";
}
else
echo "duplicate";
}
I think I'm writing these lines wrong:
$tempcart = unserialize($this->Session->read("cart"));
$this->Session->write("cart", serialize($cart));
as I'm not getting data from the session.
You are trying to add the whole Cart object to the session.
You should just add an array, like
$cart[] = array(
'productId' => $productId,
'createdAt' => date('Y-m-d H:i:s')
);
If you need to add an object to a session, you can use __sleep and __wakeup magic functions but I think in this case it's better to just add only the product id and date to the session.

Use Tierprices of other customergroup

i'm trying to get my pricing extension working but i'm stucking at the tierprices.
If a visitor comes to my site i added a paramter to the cookie.
Example: http://www.foo.com/category/product.html?sidx=5
Now the visitor enters my site with the sidx parameter. Now the Observer: catalog_product_get_final_price sets the finalprice with the first tierprice of this Product of Customergroup 5.
The Customergroup of the visitor is still NOT LOGGED IN. Now i need the other tierprices of the Customergroup ID 5 without registering.
I have googled a lot to find a solution for that but i don't get the point.
Best Regards
boti
If you want to get the Tier prices for any product:
$product = Mage::getModel('catalog/product')->load(PRODUCT_ID_HERE);
$tierPrices = $product->getData('tier_price');
if (!is_array($tierPrices)) {
$tierPrices = array();
}
$result = array();
foreach ($tierPrices as $tierPrice) {
$row = array();
$row['customer_group_id'] = (empty($tierPrice['all_groups']) ? $tierPrice['cust_group'] : 'all' );
$row['website'] = ($tierPrice['website_id'] ? Mage::app()->getWebsite($tierPrice['website_id'])->getCode() : 'all');
$row['qty'] = $tierPrice['price_qty'];
$row['price'] = $tierPrice['price'];
$result[] = $row;
}
// $result now has an array of all tier prices...
// looking for cust_group = 5 would be trivial:
foreach ($tierPrices as $tierPrice) {
if($tierPrice['cust_group'] == 5) {
return $tierPrice; // this is what you want..
}
}

Resources