What could be better way to read spreadsheet (Excel File) in laravel? - laravel

I am trying to read excel file and store that data in database. This excel file is kind of template. one would be default template and this template could be changed in future. Currently i am reading that file with many if conditions .I personally think that it isn't best way to read excel file so looking for better way.
this procedure is divided into two functions
public function importManifestFile(Request $request)
{
$path = $request->file('manifest_file')->getRealPath();
$spreadsheet = IOFactory::load($path);
$sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
foreach ($sheetData as $rows => $ManifestConsignments) {
if ($rows >= 9 && $rows <= 37) {
$this->manifestConsignment($ManifestConsignments);
}
}
}
//import file manifest consignment function
public function manifestConsignment($ManifestConsignments)
{
$consignment = new Consignment;
foreach ($ManifestConsignments as $key => $ManifestConsignment) {
if ($key == 'A') {
}
if ($key == 'B') {
$consignment->delivery_date = $ManifestConsignment;
}
if ($key == 'C') {
$addressId = $ManifestConsignment;
}
if ($key == 'D') {
$companyName = $ManifestConsignment;
}
if ($key == 'E') {
$streetAddress = $ManifestConsignment;
}
if ($key == 'F') {
$suburb = $ManifestConsignment;
}
if ($key == 'G') {
$state = $ManifestConsignment;
}
if ($key == 'H') {
$postCode = $ManifestConsignment;
}
if (isset($postCode)) {
if (Address::where('company_name', $companyName)->where('street_address', $streetAddress)->where('suburb', $suburb)->where('state', $state)->where('postcode', $postCode)->exists()) {
$deliveryAddress = Address::where('company_name', $companyName)->where('street_address', $streetAddress)->where('suburb', $suburb)->where('state', $state)->where('postcode', $postCode)->first();
$deliveryAddressId = $deliveryAddress->id;
$consignment->delivery_address = $deliveryAddressId;
unset($postCode);
} else {
$address = new Address;
$address->company_name = $companyName;
$address->street_address = $streetAddress;
$address->suburb = $suburb;
$address->postcode = $postCode;
$address->state = $state;
$address->save();
$consignment->delivery_address = $address->id;
unset($postCode);
}
if ($key == 'I') {
$consignment->carton = $ManifestConsignment;
}
if ($key == 'J') {
$consignment->pallet = $ManifestConsignment;
}
if ($key == 'K') {
$consignment->weight = $ManifestConsignment;
}
if ($key == 'L') {
$consignment->invoice_value = $ManifestConsignment;
}
if ($key == 'M') {
if (!empty($ManifestConsignment)) {
$consignment->cash_on_delivery = $ManifestConsignment;
}
}
if ($key == 'N') {
$consignment->product_type_id = 1;
}
if ($key == 'O') {
$consignment->comment = $ManifestConsignment;
}
$consignment->customer_id =1;
$consignment->status = 'In Warehouse';
$consignment->product_type_id = 1;
$consignment->save();
}
}
}
$key
in code is column name of excel file . i am checking what is column name and storing data according to that.

Related

multiple orderby sorting with pagination in laravel not working

I wrote the code snippet inside my Laravel controller and I want to sort the products by product number first and then sort the previously sorted products by inventory.
My problem is that the first sort is executed inside the written command but the second sort does not happen.
My code snippet is as follows:
DB::statement("SET SQL_MODE=''");//this is for fix groupby error!
$productdetail = Sa_product::leftJoin('sa_product_allproperties', 'sa_products.productid', 'sa_product_allproperties.product_id')->where('sa_products.product_status', '1');
if (isset($data['static']) && $data['static']['search_products'] != '') {
$search_word = $data['static']['search_products'];
DB::statement("SET SQL_MODE=''");//this is for fix groupby error!
$exploded_word = explode(',', $search_word);
$counter = 0;
$productdetail = $productdetail->where(function ($q) use ($exploded_word, $counter) {
$counter = 0;
foreach ($exploded_word as $word) {
if ($counter == 0) {
$q->where('sa_products.title', 'LIKE', "%{$word}%");
} else {
$q->orwhere('sa_products.title', 'LIKE', "%{$word}%");
}
$counter++;
}
});
}
$data['staticcats'] = explode(',', $data['static']['product_cats']);
if (isset($data['static']) && $data['static'] != '') {
$explodecats = explode(',', $data['static']['product_cats']);
unset($explodecats[0]);
array_pop($explodecats);
} else {
$explodecats = [];
}
if (isset($explodecats) && $explodecats != []) {
$counter = 0;
$productdetail = $productdetail->where(function ($q1) use ($explodecats, $counter) {
$counter = 0;
foreach ($explodecats as $cats) {
if ($counter == 0) {
$q1->where('sa_products.catid', 'LIKE', "%,{$cats},%");
} else {
$q1->orWhere('sa_products.catid', 'LIKE', "%,{$cats},%");
}
$counter++;
}
});
$productdetail = $productdetail->orderBy('visited_counter', 'DESC');
}
$data['staticcats'] = explode(',', $data['static']['product_brands']);
if (isset($data['static']) && $data['static'] != '') {
$explodebrands = explode(',', $data['static']['product_brands']);
unset($explodebrands[0]);
array_pop($explodebrands);
} else {
$explodebrands = [];
}
if (isset($explodebrands) && $explodebrands != []) {
$counter = 0;
$productdetail = $productdetail->where(function ($q2) use ($explodebrands, $counter) {
$counter = 0;
foreach ($explodebrands as $brands) {
if ($counter == 0) {
//$q1->where('brand_id','LIKE', "%,{$brands},%");
$q2->where('sa_products.brand_id', "{$brands}");
} else {
//$q1->orWhere('brand_id','LIKE', "%,{$brands},%");
$q2->orWhere('sa_products.brand_id', "{$brands}");
}
$counter++;
}
});
}
$productdetail = $productdetail->orderBy('sa_products.productid','DESC')->orderBy('sa_product_allproperties.stock_count','DESC')->groupBy('sa_products.productid')->paginate(20);
if (isset($productdetail) && $productdetail->count()>0)
{
$data['searched_products'] = $productdetail;
}
After executing the above code, the received products are sorted by product number, ie the orderBy('sa_products.productid', 'DESC') occurs, but the second sorting is done with the orderBy('sa_product_allproperties.stock_count', 'DESC') Which is not run for inventory sorting.
Can anyone help me solve this problem?

What might be best solution to get camelCase data from angular,integrate with snake_case mysql and send response in camelCase back to angular?

what i did is:
$input = $request->all();
//convert the post camelcase to snakecase
foreach ($input as $key => $val) {
$newKey = snake_case($key);
$input[$newKey] = $val;
if ($newKey != $key) {
unset($input[$key]);
}
}
after integrating data,use helper function to convert snakecase to camelcase again by the following function:
function convert_snakeCase_to_CamelCase($data)
{
if ($data) {
foreach ($data as $key1 => $val1) {
$newKey1 = camel_case($key1);
if ($newKey1 != $key1) {
unset($data[$key1]);
}
$data[$newKey1] = $val1;
if (is_array($val1) && !empty($val1)) {
foreach ($val1 as $key2 => $val2) {
$newKey2 = camel_case($key2);
if ($newKey2 != $key2) {
unset($data[$newKey1][$key2]);
}
$data[$newKey1][$newKey2] = $val2;
if (is_array($val2) && !empty($val2)) {
foreach ($val2 as $key3 => $val3) {
$newKey3 = camel_case($key3);
if ($newKey3 != $key3) {
unset($data[$newKey1][$newKey2][$key3]);
}
$data[$newKey1][$newKey2][$newKey3] = $val3;
if (is_array($val3) && !empty($val3)) {
foreach ($val3 as $key4 => $val4) {
$newKey4 = camel_case($key4);
if ($newKey4 != $key4) {
unset($data[$newKey1][$newKey2][$newKey3][$key4]);
}
$data[$newKey1][$newKey2][$newKey3][$newKey4] = $val4;
if (is_array($val4) && !empty($val4)) {
foreach ($val4 as $key5 => $val5) {
$newKey5 = camel_case($key5);
if ($newKey5 != $key5) {
unset($data[$newKey1][$newKey2][$newKey3][$newKey4][$key5]);
}
$data[$newKey1][$newKey2][$newKey3][$newKey4][$newKey5] = $val5;
if (is_array($val5) && !empty($val5)) {
foreach ($val5 as $key6 => $val6) {
$newKey6 = camel_case($key6);
if ($newKey6 != $key6) {
unset($data[$newKey1][$newKey2][$newKey3][$newKey4][$newKey5][$key6]);
}
$data[$newKey1][$newKey2][$newKey3][$newKey4][$newKey5][$newKey6] = $val6;
}
}
}
}
}
}
}
}
}
}
}
}
return $data;
}
its working absolutely fine.I was wondering is there any solution better plugins for angular or laravel to convert the post data and send response data in required case?

Get category name by category id without if else statement

public function shirts($type = '') {
{
if ($type == 'glass') {
$shirt = Product::where('category_id', '1') - > get();
}
elseif($type == 'ic') {
$shirt = Product::where('category_id', '2') - > get();
}
elseif($type == 'cover') {
$shirt = Product::where('category_id', '3') - > get();
} else {
$shirt = Product::all();
}
$products = Category::find($shirt);
return view('front.shirt', compact('products', 'shirt'));
}
}
can some one help me in minimising this Controller I don't want to use if else statement

How to remove article ID from url in Joomla 1.5?

Using standard SEF in Joomla 1.5 I have links like: mysite.com/news/36-good-news-tooday.
I need to remove article ID from url and get something like this: mysite.com/news/good-news-today.
Note: It means I don't want use any plugins (like HP Router etc.)
I want edit Joomla own SEF.
UPD: Finally I found desicion. Here is full listing of router.php, wich you can find in components/com_content
<?php
/**
* #version $Id: router.php 14401 2010-01-26 14:10:00Z louis $
* #package Joomla
* #copyright Copyright (C) 2005 - 2010 Open Source Matters. All rights reserved.
* #license GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
function ContentBuildRoute(&$query)
{
$segments = array();
$menu = &JSite::getMenu();
if (empty($query['Itemid'])) {
$menuItem = &$menu->getActive();
} else {
$menuItem = &$menu->getItem($query['Itemid']);
}
$mView = (empty($menuItem->query['view']))? null : $menuItem->query['view'];
$mCatid = (empty($menuItem->query['catid']))? null : $menuItem->query['catid'];
$mId = (empty($menuItem->query['id']))? null : $menuItem->query['id'];
if(isset($query['task'])) {
return $segments;
}
if(isset($query['view']))
{
$view = $query['view'];
if(empty($query['Itemid'])) {
$segments[] = $query['view'];
}
unset($query['view']);
};
if (($mView == 'article') and (isset($query['id'])) and ($mId == intval($query['id']))) {
unset($query['view']);
unset($query['catid']);
unset($query['id']);
}
if (isset($view) and ($view == 'section' && !empty($query['Itemid']))) {
if (($mView != 'section') or ($mView == 'section' and $mId != intval($query['id']))) {
$segments[] = 'section';
unset($query['Itemid']);
}
}
if (isset($view) and $view == 'category') {
if ($mId != intval($query['id']) || $mView != $view) {
$temp = explode(':',$query['id']);
if(count($temp) > 1)
{
$query['id'] = $temp[1];
}
$segments[] = $query['id'];
}
unset($query['id']);
}
if (isset($query['catid'])) {
if ((($view == 'article') and ($mView != 'category') and ($mView != 'article') and ($mCatid != intval($query['catid'])))) {
$temp = explode(':',$query['catid']);
if(count($temp) > 1)
{
$query['catid'] = $temp[1];
}
$segments[] = $query['catid'];
}
unset($query['catid']);
};
if(isset($query['id'])) {
if (empty($query['Itemid'])) {
$temp = explode(':',$query['id']);
if(count($temp) > 1)
{
$query['id'] = $temp[1];
}
$segments[] = $query['id'];
} else {
if (isset($menuItem->query['id'])) {
if($query['id'] != $mId) {
$temp = explode(':',$query['id']);
if(count($temp) > 1)
{
$query['id'] = $temp[1];
}
$segments[] = $query['id'];
}
} else {
$temp = explode(':',$query['id']);
if(count($temp) > 1)
{
$query['id'] = $temp[1];
}
$segments[] = $query['id'];
}
}
unset($query['id']);
};
if(isset($query['year'])) {
if(!empty($query['Itemid'])) {
$segments[] = $query['year'];
unset($query['year']);
}
};
if(isset($query['month'])) {
if(!empty($query['Itemid'])) {
$segments[] = $query['month'];
unset($query['month']);
}
};
if(isset($query['layout']))
{
if(!empty($query['Itemid']) && isset($menuItem->query['layout'])) {
if ($query['layout'] == $menuItem->query['layout']) {
unset($query['layout']);
}
} else {
if($query['layout'] == 'default') {
unset($query['layout']);
}
}
};
return $segments;
}
function ContentParseRoute($segments)
{
$vars = array();
$menu =& JSite::getMenu();
$item =& $menu->getActive();
$db =& JFactory::getDBO();
$count = count($segments);
if(!isset($item))
{
$vars['view'] = $segments[0];
$vars['id'] = $segments[$count - 1];
if($vars['view'] == 'article')
{
$query = 'SELECT id FROM #__content WHERE alias = '.$db->Quote($vars['id']);
} elseif($vars['view'] == 'category') {
$query = 'SELECT id FROM #__categories WHERE section > 0 && alias = '.$db->Quote($vars['id']);
}
$db->setQuery($query);
$vars['id'] = $db->loadResult();
return $vars;
}
switch($item->query['view'])
{
case 'section' :
{
if($count == 1) {
$vars['view'] = 'category';
if(isset($item->query['layout']) && $item->query['layout'] == 'blog') {
$vars['layout'] = 'blog';
}
}
if($count == 2) {
$vars['view'] = 'article';
$vars['catid'] = $segments[$count-2];
}
$vars['id'] = $segments[$count-1];
} break;
case 'category' :
{
$vars['id'] = $segments[$count-1];
$vars['view'] = 'article';
} break;
case 'frontpage' :
{
$vars['id'] = $segments[$count-1];
$vars['view'] = 'article';
} break;
case 'article' :
{
$vars['id'] = $segments[$count-1];
$vars['view'] = 'article';
} break;
case 'archive' :
{
if($count != 1)
{
$vars['year'] = $count >= 2 ? $segments[$count-2] : null;
$vars['month'] = $segments[$count-1];
$vars['view'] = 'archive';
} else {
$vars['id'] = $segments[$count-1];
$vars['view'] = 'article';
}
}
}
$alias = explode(':', $vars['id']);
if((int) $alias[0] > 0)
{
$vars['id'] = $alias[0];
} else {
if(count($alias) > 1)
{
$vars['id'] = $alias[0].'-'.$alias[1];
}
if($vars['view'] == 'article')
{
$query = 'SELECT id FROM #__content WHERE alias = '.$db->Quote($vars['id']);
} elseif($vars['view'] == 'category') {
$query = 'SELECT id FROM #__categories WHERE section > 0 && alias = '.$db->Quote($vars['id']);
}
$db->setQuery($query);
$vars['id'] = $db->loadResult();
}
return $vars;
}
I'm not an author! Router code was modified by Marvin Ryan.
This code works perfect in most of cases!
But I have some problems with JoomFish language toggle.
It have links like www.mysite.com/news/22
So I get only article ID, not article alias. This problem is still actual!
Create menu items for every article.

magento final_price,min_price,max_price wrong values insertion

Hi
i have problem with the final_price,min_price,max_price in the catalog_product_index_price table its is wrongly inserting the values after function save() during import.
The file is app\code\core\Mage\Catalog\Model\Convert\Adapter\Product.php
The control goes to finish() function
public function finish()
{
Mage::dispatchEvent('catalog_product_import_after', array());
$entity = new Varien_Object();
Mage::getSingleton('index/indexer')->processEntityAction(
$entity, self::ENTITY, Mage_Index_Model_Event::TYPE_SAVE
);
}
where is the insert statement to insert the value in the catalog_product_index_price table?
How this can be resolved?
My saveRow fucnction to populate database.My excel sheet contains the following additional row
Price Type:radio:1
Unit Price:absolute:2691|Case Price:absolute:12420
Unit Price:absolute:762|Case Price:absolute:7029
The save database function is
public function saveRow(array $importData)
{
$product = $this->getProductModel()
->reset();
if (empty($importData['store'])) {
if (!is_null($this->getBatchParams('store'))) {
$store = $this->getStoreById($this->getBatchParams('store'));
} else {
$message = Mage::helper('catalog')->__('Skipping import row, required field "%s" is not defined.', 'store');
Mage::throwException($message);
}
}
else {
$store = $this->getStoreByCode($importData['store']);
}
if ($store === false) {
$message = Mage::helper('catalog')->__('Skipping import row, store "%s" field does not exist.', $importData['store']);
Mage::throwException($message);
}
if (empty($importData['sku'])) {
$message = Mage::helper('catalog')->__('Skipping import row, required field "%s" is not defined.', 'sku');
Mage::throwException($message);
}
$product->setStoreId($store->getId());
$productId = $product->getIdBySku($importData['sku']);
if ($productId) {
$product->load($productId);
}
else {
$productTypes = $this->getProductTypes();
$productAttributeSets = $this->getProductAttributeSets();
/**
* Check product define type
*/
if (empty($importData['type']) || !isset($productTypes[strtolower($importData['type'])])) {
$value = isset($importData['type']) ? $importData['type'] : '';
$message = Mage::helper('catalog')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'type');
Mage::throwException($message);
}
$product->setTypeId($productTypes[strtolower($importData['type'])]);
/**
* Check product define attribute set
*/
if (empty($importData['attribute_set']) || !isset($productAttributeSets[$importData['attribute_set']])) {
$value = isset($importData['attribute_set']) ? $importData['attribute_set'] : '';
$message = Mage::helper('catalog')->__('Skip import row, the value "%s" is invalid for field "%s"', $value, 'attribute_set');
Mage::throwException($message);
}
$product->setAttributeSetId($productAttributeSets[$importData['attribute_set']]);
foreach ($this->_requiredFields as $field) {
$attribute = $this->getAttribute($field);
if (!isset($importData[$field]) && $attribute && $attribute->getIsRequired()) {
$message = Mage::helper('catalog')->__('Skipping import row, required field "%s" for new products is not defined.', $field);
Mage::throwException($message);
}
}
}
$this->setProductTypeInstance($product);
if (isset($importData['category_ids'])) {
$product->setCategoryIds($importData['category_ids']);
}
foreach ($this->_ignoreFields as $field) {
if (isset($importData[$field])) {
unset($importData[$field]);
}
}
if ($store->getId() != 0) {
$websiteIds = $product->getWebsiteIds();
if (!is_array($websiteIds)) {
$websiteIds = array();
}
if (!in_array($store->getWebsiteId(), $websiteIds)) {
$websiteIds[] = $store->getWebsiteId();
}
$product->setWebsiteIds($websiteIds);
}
if (isset($importData['websites'])) {
$websiteIds = $product->getWebsiteIds();
if (!is_array($websiteIds)) {
$websiteIds = array();
}
$websiteCodes = explode(',', $importData['websites']);
foreach ($websiteCodes as $websiteCode) {
try {
$website = Mage::app()->getWebsite(trim($websiteCode));
if (!in_array($website->getId(), $websiteIds)) {
$websiteIds[] = $website->getId();
}
}
catch (Exception $e) {}
}
$product->setWebsiteIds($websiteIds);
unset($websiteIds);
}
$custom_options = array();
foreach ($importData as $field => $value) {
if (in_array($field, $this->_inventoryFields)) {
continue;
}
if (in_array($field, $this->_imageFields)) {
continue;
}
$attribute = $this->getAttribute($field);
if (!$attribute) {
/* CUSTOM OPTION CODE */
if(strpos($field,':')!==FALSE && strlen($value)) {
$values=explode('|',$value);
if(count($values)>0) {
#list($title,$type,$is_required,$sort_order) = explode(':',$field);
$title = ucfirst(str_replace('_',' ',$title));
$custom_options[] = array(
'is_delete'=>0,
'title'=>$title,
'previous_group'=>'',
'previous_type'=>'',
'type'=>$type,
'is_require'=>$is_required,
'sort_order'=>$sort_order,
'values'=>array()
);
foreach($values as $v) {
$parts = explode(':',$v);
$title = $parts[0];
if(count($parts)>1) {
$price_type = $parts[1];
} else {
$price_type = 'fixed';
}
if(count($parts)>2) {
$price = $parts[2];
} else {
$price =0;
}
if(count($parts)>3) {
$sku = $parts[3];
} else {
$sku='';
}
if(count($parts)>4) {
$sort_order = $parts[4];
} else {
$sort_order = 0;
}
switch($type) {
case 'file':
/* TODO */
break;
case 'field':
case 'area':
$custom_options[count($custom_options) - 1]['max_characters'] = $sort_order;
/* NO BREAK */
case 'date':
case 'date_time':
case 'time':
$custom_options[count($custom_options) - 1]['price_type'] = $price_type;
$custom_options[count($custom_options) - 1]['price'] = $price;
$custom_options[count($custom_options) - 1]['sku'] = $sku;
break;
case 'drop_down':
case 'radio':
case 'checkbox':
case 'multiple':
default:
$custom_options[count($custom_options) - 1]['values'][]=array(
'is_delete'=>0,
'title'=>$title,
'option_type_id'=>-1,
'price_type'=>$price_type,
'price'=>$price,
'sku'=>$sku,
'sort_order'=>$sort_order,
);
break;
}
}
}
}
/* END CUSTOM OPTION CODE */
continue;
}
$isArray = false;
$setValue = $value;
if ($attribute->getFrontendInput() == 'multiselect') {
$value = explode(self::MULTI_DELIMITER, $value);
$isArray = true;
$setValue = array();
}
if ($value && $attribute->getBackendType() == 'decimal') {
$setValue = $this->getNumber($value);
}
if ($attribute->usesSource()) {
$options = $attribute->getSource()->getAllOptions(false);
if ($isArray) {
foreach ($options as $item) {
if (in_array($item['label'], $value)) {
$setValue[] = $item['value'];
}
}
} else {
$setValue = false;
foreach ($options as $item) {
if ($item['label'] == $value) {
$setValue = $item['value'];
}
}
}
}
$product->setData($field, $setValue);
}
if (!$product->getVisibility()) {
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
}
$stockData = array();
$inventoryFields = isset($this->_inventoryFieldsProductTypes[$product->getTypeId()])
? $this->_inventoryFieldsProductTypes[$product->getTypeId()]
: array();
foreach ($inventoryFields as $field) {
if (isset($importData[$field])) {
if (in_array($field, $this->_toNumber)) {
$stockData[$field] = $this->getNumber($importData[$field]);
}
else {
$stockData[$field] = $importData[$field];
}
}
}
$product->setStockData($stockData);
$imageData = array();
foreach ($this->_imageFields as $field) {
if (!empty($importData[$field]) && $importData[$field] != 'no_selection') {
if (!isset($imageData[$importData[$field]])) {
$imageData[$importData[$field]] = array();
}
$imageData[$importData[$field]][] = $field;
}
}
foreach ($imageData as $file => $fields) {
try {
$product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . trim($file), $fields);
}
catch (Exception $e) {}
}
$product->setIsMassupdate(true);
$product->setExcludeUrlRewrite(true);
$product->save();
/* Remove existing custom options attached to the product */
foreach ($product->getOptions() as $o) {
$o->getValueInstance()->deleteValue($o->getId());
$o->deletePrices($o->getId());
$o->deleteTitles($o->getId());
$o->delete();
}
/* Add the custom options specified in the CSV import file */
if(count($custom_options)) {
foreach($custom_options as $option) {
try {
$opt = Mage::getModel('catalog/product_option');
$opt->setProduct($product);
$opt->addOption($option);
$opt->saveOptions();
}
catch (Exception $e) {}
}
}
return true;
}
This section of the code has been quite well tested, so it's unlikely (though conceivable) that this is a bug that you need to correct in the indexer. Can you provide more detail about the discrepancy that you are seeing?
There is a very good chance that you are seeing unexpected results because of some product being enabled/disabled, etc etc.

Resources