Laravel 5.3 database transaction issue? - laravel

I have used more time with Laravel 5.0 on database transaction but when I change to Laravel 5.3.* it not work as I want even I have disabled commit() method all data still continue insert into database.
if ($request->isMethod('post')) {
DB::beginTransaction();
$cats = new Cat();
$cats->parent_id = $this->request->input('category_id');
$cats->status = ($this->request->input('status')) ? $this->request->input('status') : 0;
if ($res['cat'] = $cats->save()) {
$catD = new CategoryDescriptions();
$catD->category_id = $cats->id;
$catD->language_id = 1;
$catD->name = $this->request->input('en_name');
if ($res['cat2'] = $catD->save()) {
$catD2 = new CategoryDescriptions();
$catD2->category_id = $cats->id;
$catD2->language_id = 2;
$catD2->name = $this->request->input('kh_name');
$res['all'] = $catD2->save();
}
}
if ($res) {
//DB::commit();
return $res;
}
return [false];
}

Check this line ($res['cat'] is a boolean):
if($res['cat'] = $cats->save()) {
And this ($res is an array. You compare an array as boolean!):
if($res){
The right condition should be:
$res = array(); // the first line of your method
// .... your http method check, start transaction, etc.
if (!in_array(false, $res, true)) { // check if array doesn't contain 'false values'
DB::commit();
}

Related

Display large array in laravel blade in too much time

so i got imported my large excel file with huge informations with 1 sec and i did get all the information i need to display within 1 sec to , but i got a big probleme when displaying the array in the view coz i m testing if the cells are correct or not i m using 5 ifs and 3 foreach and it takes mote than 2 mins , i need help to display all the info in a short time this is my array , and thanks
and there is my code of the view which takes to much time to display infos
and thanks
//here we get our final result of true and false fields
$finale_array = [];
// here we get all our
$current_table2 = [];
$results_applied = [];
$current_result = [];
$columns = SCHEMA::getColumnListing('imports');
// here we get all our conditions
$conditions = DB::table('conditions')->select('number', 'field', 'value')->get();
// here we get all our data
$imports = DB::table('imports')->get();
$results = DB::table('results')->get();
$x = 0;
$default_value = 0;
foreach ($imports as $key => $imported) {
$res = get_object_vars($imported);
foreach ($conditions as $value) {
$array = get_object_vars($value);
$result = $this->test($columns, $array['field']); // the result of our test function
if ($result == "ok") {
if ($res[$array['field']] == $array['value']) {
foreach ($results as $value_result) {
$res_resultat = get_object_vars($value_result);
$test_field = $this->test($columns, $res_resultat['field']);
// testing if the condtion numder match with the result number
if (($res_resultat['condition_number'] == $array['number'])) {
if (($test_field == 'ok')) {
if ($res['id'] != $default_value) {
// here test if the difference between the id and the default value is different from the current id to insert
if (($res['id'] - $default_value) != $res['id']) {
array_push($current_table2, $results_applied);
array_push($finale_array, $current_table2);
$current_table2 = [];
$results_applied = [];
$default_value = $res['id'];
}
$current_table2 = [$res, $res['id']];
}
$current_result = [$res_resultat['field'], $res[$res_resultat['field']]];
if ($res_resultat['value'] == $res[$res_resultat['field']]) {
$current_result[2] = 'true';
$current_result[3] = $res_resultat['value'];
} else {
$current_result[2] = 'false';
$current_result[3] = $res_resultat['value'];
}
$current_result[4] = $array['number'];
array_push($results_applied, $current_result);
}
}
}
}
}
}
$default_value = $res['id'];
}
array_push($current_table2, $results_applied);
array_push($finale_array, $current_table2);
dd($finale_array);
return view('Appliedconditions', ['imports' => $finale_array, 'columns' => $columns]);
}
From what I can see, you are recovering all the data without paging it.
You must paginate the data using the paginate(#elements_per_page) directive in your query, where #elements_per_page is the number of elements you want to display per page.
For example:
$elements = Elements::select('*')->paginate(10);
and in your blade view you can retreive pagination links after the closing table tag in this way: {{ $elements->links() }}

Passing multiple values using

I want to pass multiple values in single column of database.
I have two tables (Schedule & Days). In form I select days when I select multiple days then I should add in db multiple. But it add only one day
public function store(Request $request)
{
$schedule = new menu;
$days = new day;
$sensor = new sensor;
$schedule->scheduleName = $request->name;
$schedule->start_time = $request->start_time;
$schedule->end_time = $request->end_time;
$schedule->timestamps = false;
$schedule->s_daytime = $request->s_daytime;
$schedule->e_daytime = $request->e_daytime;
$days->days = $request->days;
$days->timestamps = false;
$sensor->timestamps = false;
$sensor->sensor = $request->sensor;
$schedule->save();
$days->schedule_id = $schedule->id;
$days->save();
$sensor->schedule_id = $schedule->id;
$sensor->save();
return view('store');
}
What you can do is you can pass multiple days in an array and store the array in json format on your DB. here is the snippets.
$days_list = $request->days_list;
//for edit previous data
if(!empty($days->days_list)){
$arr = json_decode($days->days_list);
if(in_array($request->days, $arr)){
$data['success'] = false;
$data['message'] = 'This Day is already on your schedule
list.';
return $data;
}
array_push($arr, $days_list);
$days->days_list = json_encode($arr);
}
// for adding new data
else{
$days->days_list = json_encode(array($request->days_list));
}
$days->save();
```

Phalcon use Oracle views

In a Phalcon project, I have multiple database in Oracle and mySQL with number of tables and views. Created models for corresponding tables and views. But unable to access views. I initialize in model below:
public function initialize()
{
$this->setConnectionService('dbBznes');
$this->setSchema('POLICY');
$this->setSource("BUSINESS_ALL");
}
As per the comments, this is apparently a metadata issue and the default metadata strategy is introspection and is attempting to check if the table exists. You can set up your own metadata strategy like so:
$di['modelsMetadata'] = function()
{
$metadata = new \Phalcon\Mvc\Model\MetaData\Memory();
$metadata->setStrategy(
new MyIntrospectionStrategy()
);
return $metadata;
};
"Memory" in this case means don't use any sort of metadata caching. This goes off into another tangent as you can cache in many ways for more speed in production, etc.
As for the MyIntrospectionStrategy class above, it represents your own class based on Phalcon's Introspection strategy which attempts to analyze the database to figure out the fields and their types involved with the table.
I believe I converted Phalcon\Mvc\Model\MetaData\Strategy\Introspection from Zephir to PHP correctly as follows:
class MyIntrospectionStrategy implements \Phalcon\Mvc\Model\MetaData\StrategyInterface
{
public final function getMetaData(\Phalcon\Mvc\ModelInterface $model, \Phalcon\DiInterface $dependencyInjector)
{
$schema = $model->getSchema();
$table = $model->getSource();
$readConnection = $model->getReadConnection();
if( !$readConnection->tableExists($table, $schema) )
{
if($schema)
{
$completeTable = $schema . "'.'" . $table;
} else {
$completeTable = $table;
}
throw new \Phalcon\Mvc\Model\Exception(
"Table '" . $completeTable . "' doesn't exist in database when dumping meta-data for " . get_class($model)
);
}
$columns = $readConnection->describeColumns($table, $schema);
if( !count($columns) )
{
if($schema)
{
$completeTable = $schema . "'.'" . $table;
} else {
$completeTable = $table;
}
/**
* The table not exists
*/
throw new \Phalcon\Mvc\Model\Exception(
"Cannot obtain table columns for the mapped source '" . completeTable . "' used in model " . get_class(model)
);
}
$attributes = [];
$primaryKeys = [];
$nonPrimaryKeys = [];
$numericTyped = [];
$notNull = [];
$fieldTypes = [];
$fieldBindTypes = [];
$automaticDefault = [];
$identityField = false;
$defaultValues = [];
$emptyStringValues = [];
foreach($columns as $column)
{
$fieldName = $column->getName();
$attributes[] = $fieldName;
if ($column->isPrimary() === true)
{
$primaryKeys[] = $fieldName;
} else {
$nonPrimaryKeys[] = $fieldName;
}
if ($column->isNumeric() === true)
{
$numericTyped[$fieldName] = true;
}
if ($column->isNotNull() === true)
{
$notNull[] = $fieldName;
}
if ($column->isAutoIncrement() === true)
{
$identityField = $fieldName;
}
$fieldTypes[$fieldName] = $column->getType();
$fieldBindTypes[$fieldName] = $column->getBindType();
$defaultValue = $column->getDefault();
if ($defaultValue !== null || $column->isNotNull() === false)
{
if ( !$column->isAutoIncrement() )
{
$defaultValues[$fieldName] = $defaultValue;
}
}
}
return [
\Phalcon\Mvc\Model\MetaData::MODELS_ATTRIBUTES => $attributes,
\Phalcon\Mvc\Model\MetaData::MODELS_PRIMARY_KEY => $primaryKeys,
\Phalcon\Mvc\Model\MetaData::MODELS_NON_PRIMARY_KEY => $nonPrimaryKeys,
\Phalcon\Mvc\Model\MetaData::MODELS_NOT_NULL => $notNull,
\Phalcon\Mvc\Model\MetaData::MODELS_DATA_TYPES => $fieldTypes,
\Phalcon\Mvc\Model\MetaData::MODELS_DATA_TYPES_NUMERIC => $numericTyped,
\Phalcon\Mvc\Model\MetaData::MODELS_IDENTITY_COLUMN => $identityField,
\Phalcon\Mvc\Model\MetaData::MODELS_DATA_TYPES_BIND => $fieldBindTypes,
\Phalcon\Mvc\Model\MetaData::MODELS_AUTOMATIC_DEFAULT_INSERT => $automaticDefault,
\Phalcon\Mvc\Model\MetaData::MODELS_AUTOMATIC_DEFAULT_UPDATE => $automaticDefault,
\Phalcon\Mvc\Model\MetaData::MODELS_DEFAULT_VALUES => $defaultValues,
\Phalcon\Mvc\Model\MetaData::MODELS_EMPTY_STRING_VALUES => $emptyStringValues
];
}
public final function getColumnMaps(\Phalcon\Mvc\ModelInterface $model, \Phalcon\DiInterface $dependencyInjector)
{
$orderedColumnMap = null;
$reversedColumnMap = null;
if (method_exists($model, 'columnMap'))
{
$userColumnMap = $model->columnMap();
if ( gettype($userColumnMap) != 'array')
{
// Bad grammer directly in cphalcon :sadface:
throw new \Phalcon\Mvc\Model\Exception('columnMap() not returned an array');
}
$reversedColumnMap = [];
$orderedColumnMap = $userColumnMap;
foreach($userColumnMap as $name => $userName)
{
$reversedColumnMap[$userName] = $name;
}
}
return [$orderedColumnMap, $reversedColumnMap];
}
}
I have not tested this.
As far as adding support for views to be treated like tables, the change might be as simple as:
Before:
if( !$readConnection->tableExists($table, $schema) )
After:
if( !$readConnection->tableExists($table, $schema) && !$readConnection->viewExists($table, $schema) )
If this doesn't work due to logic choking with describeColumns, you might need to write something specific for working with views in Oracle for this dialect.
As far as other solutions, you can provide your own metadata method directly on the model by specifying your ownmetaData method directly on it.
Another solution is to use annotations instead of introspection for metadata.
Then you'd place your metadata as comments in the code for Phalcon to parse.
If you continue to run into problems with Database Views, just run it as raw SQL rather than attempting to use the ORM to do it. You can simply define a new method on your model to run the raw SQL.

Strange error session get destroyed

I have a problem when I execute controller method it process controller code but destroy all session including user.
So after process thus controller and I try to open home page, there is no logged in account.
I'm sure no destroy session code, nor logout code in my controller. and I can say this is not about session expired.
I don't know what wrong is this about code, yii2 configuration or logic, but is someone have similar problem in past?
Hope you can guide me to solve this problem.
If you need more information, please let me know.
This not related to code maybe, but here is my controller code.
<?php
namespace frontend\controllers;
use Yii;
use common\models\TbCustomer;
use yii\web\Controller;
use common\models\Model;
use common\models\VwProdukAgent;
use common\models\TbCart;
use yii\helpers\VarDumper;
use common\models\VwProduk;
use yii\data\ActiveDataProvider;
use common\models\VwProdukCustomer;
use common\models\TbCustomerShipment;
use common\component\BeoHelper;
use common\models\TbProdukEkspedisi;
use common\models\TbKota;
use yii\helpers\Url;
/**
* CustomerController implements the CRUD actions for TbCustomer model.
*/
class Pengiriman1Controller extends Controller
{
public function beforeAction($action)
{
Yii::$app->timeZone = 'Asia/Jakarta';
if(Yii::$app->user->isGuest)
{
//$url = Url::to([['home'],'message'=>'Anda Harus Login Terlebih Dahulu']);
\Yii::$app->getSession()->setFlash('message', \Yii::t('app', 'Anda Harus Login Terlebih Dahulu'));
$this->goHome();
return FALSE;
}
//if ($action->id == 'my-method') {
$this->enableCsrfValidation = false;
// }
return parent::beforeAction($action);
}
public function actionIndex()
{
//get alamat customer
//$lsalamat = array();
if(!\Yii::$app->user->isGuest)
{
BeoHelper::refreshCart();
//cek cart kosong atau tidak
if(isset(\Yii::$app->session['produkcart']))
{
$lsproduk = \Yii::$app->session['produkcart'];
if (count($lsproduk)<1)
{
\Yii::$app->getSession()->setFlash('message',"silahkan berbelanja terlebih dahulu");
return $this->redirect(Url::to(['cart/index']));
}
}
$customer_id = Yii::$app->user->id;
$message = '';
$model = null;
if(\Yii::$app->request->post('opsi_alamat',null)!=null)
{
$opsi_pengiriman = \Yii::$app->request->post('opsi_alamat',null);
//return $opsi_pengiriman;
if($opsi_pengiriman == 'new')
{
$model = new TbCustomerShipment();
$model->load(Yii::$app->request->post());
$model->customer_id = $customer_id;
if($model->save())
{
\Yii::$app->session['shipemenadd'] = $model;
//get kurir preselected
if(isset(\Yii::$app->session['produkcart']))
{
$hargatotal = 0;
$lsproduk = \Yii::$app->session['produkcart'];
$i=0;
$lsprodukedit = array();
foreach ($lsproduk as $produk)
{
//pre selected
$pengiriman = TbProdukEkspedisi::find()->where(['produk_id' => $produk->produk_id])->one();
$kode = $pengiriman->idEkspedisi->kode_ekspedisi;
$service = $pengiriman->idEkspedisi->service;
$produk->kurir = $kode;
$kota_asal = TbKota::find()->where("kota_id = $produk->kota_id ")->one();
$kota_tujuan = TbKota::find()->where("kota_id = $model->kota_id ")->one();
$berat_produk = $produk->kuantitas *$produk->berat_produk;
$berat_produk = round($berat_produk);
$result = BeoHelper::getCostEkspedisi($kota_asal->api_id, $kota_tujuan->api_id, $berat_produk, $kode,$service,$produk->produk_id);
if(count($result)!=0)
{
$produk->harga_kurir = $result[0]['value'];
$produk->estimasi_sampai = $result[0]['etd'];
}
else
{
$message = "pilihan kurir untuk lokasi tersebut tidak tersedia";
}
//return VarDumper::dump($result);
$lsprodukedit[$i++] = $produk;
$hargatotal += $produk->kuantitas * $produk->harga_agen;
}
\Yii::$app->session['produkcart'] = $lsprodukedit;
}
if(isset(Yii::$app->session['shipemenadd'])){
return "exists";
}else{
return "doesn't exist";
}
//return $this->redirect(['pengiriman2/index','message'=>$message]);
//print_r(Yii::$app->session['shipemenadd']);
}
//else
//{
// VarDumper::dump($model);
//}
}
else
{
$pengiriman_selected = TbCustomerShipment::find()->where("customer_shipment_id = $opsi_pengiriman")->one();
\Yii::$app->session['shipemenadd'] = $pengiriman_selected;
if(isset(\Yii::$app->session['produkcart']))
{
$hargatotal = 0;
$lsproduk = \Yii::$app->session['produkcart'];
$i=0;
$lsprodukedit = array();
foreach ($lsproduk as $produk)
{
//pre selected
$pengiriman = TbProdukEkspedisi::find()->where("produk_id =$produk->produk_id")->one();
$kode = $pengiriman->idEkspedisi->kode_ekspedisi;
$service = $pengiriman->idEkspedisi->service;
$produk->kurir = $kode;
//get kota id rajaongkir
$kota_asal = TbKota::find()->where("kota_id = $produk->kota_id ")->one();
$kota_tujuan = TbKota::find()->where("kota_id = $pengiriman_selected->kota_id ")->one();
//$result = BeoHelper::getCostEkspedisi($kota_asal->api_id, $kota_tujuan->api_id, $produk->berat_produk, $kode,$service);
//return VarDumper::dump($result);
//if(count($result)!=0)
//{
//$produk->harga_kurir = $result[0]['value'];
//$produk->estimasi_sampai = $result[0]['etd'];
$produk->harga_kurir = 0;
$produk->estimasi_sampai = 0;
//}
//else
//{
// $message = "pilihan kuriri untuk lokasi tersebut tidak tersedia";
//}
$lsprodukedit[$i++] = $produk;
$hargatotal += $produk->kuantitas * $produk->harga_agen;
}
\Yii::$app->session['produkcart'] = $lsprodukedit;
}
return $this->redirect(['pengiriman2/index','message'=>$message]);
}
}
$lsalamat = TbCustomerShipment::find()->where(['customer_id'=>$customer_id])->all();
if(count($lsalamat)==0)
//insert to tb shipment
{
$datacustomer = TbCustomer::find()->where(['customer_id'=>$customer_id])->one();
$newalamat = new TbCustomerShipment();
$newalamat->customer_id = $customer_id;
$newalamat->kota_id = $datacustomer->kota_id;
$newalamat->kecamatan_id = $datacustomer->kecamatan_id;
$newalamat->negara_id = $datacustomer->negara_id;
$newalamat->propinsi_id = $datacustomer->propinsi_id;
$newalamat->alamat = $datacustomer->alamat;
$newalamat->shipment_name = "Alamat Rumah";
$newalamat->penerima = $datacustomer->nama;
$newalamat->hp_penerima = $datacustomer->hp;
$newalamat->save();
}
$lsalamat = TbCustomerShipment::find()->where(['customer_id'=>$customer_id])->all();
return $this->render('index',['lsalamat'=>$lsalamat,'newalamat'=> $model]);
}
else
{
return $this->goHome();
}
}
}
here is the problem
\Yii::$app->session['shipemenadd'] = $model;
it should
$currentTbCustomerShipment = TbCustomerShipment::find()->where(['customer_user_id' => $model->customer_user_id])->one(); //find latest object
Yii::$app->session['shipemenadd'] = $currentTbCustomerShipment;

Create category programmatically in multiple languages in Magento

i am tyring to add categories programmatically for german and english languages.
website-ID: 1
website store-ID: 1
view-ID english, code "en" => 1
view-ID german, code "de" => 2
$category['general']['path'] = $v['cat_name_de'];
$category['general']['name'] = $v['cat_name_de'];
$category['general']['meta_title'] = "";
$category['general']['meta_description'] = "";
$category['general']['is_active'] = 1;
$category['general']['url_key'] = urlencode($v['cat_name_de']);
$category['general']['display_mode'] = "PRODUCTS";
$category['general']['is_anchor'] = 0;
$category['category']['parent'] = $v['magento_cat_id'];
$storeId = 0; // default
$magento_subcat_id = createCategory($category, $storeId);
...
function createCategory($data, $storeId) {
echo "Erzeuge '{$data['general']['name']}' - Elternkategorie:
[{$data['category']['parent']}] ...";
$category = Mage::getModel('catalog/category');
$category->setStoreId($storeId);
if (is_array($data)) {
$category->addData($data['general']);
if (!$category->getId()) {
$parentId = $data['category']['parent'];
if (!$parentId) {
if ($storeId) {
$parentId = Mage::app()->getStore($storeId)->getRootCategoryId();
} else {
$parentId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
}
}
$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$category->setPath($parentCategory->getPath());
}
if ($useDefaults = $data['use_default']) {
foreach ($useDefaults as $attributeCode) {
$category->setData($attributeCode, null);
}
}
$category->setAttributeSetId($category->getDefaultAttributeSetId());
if (isset($data['category_products']) &&
!$category->getProductsReadonly()) {
$products = array();
parse_str($data['category_products'], $products);
$category->setPostedProducts($products);
}
try {
$category->save();
return $category->getId();
} catch (Exception $e) {
return FALSE;
}
}
}
What i am puzzling with at the moment is setting view-ID individually for passing the $category['general']['name'] for each language.
I tried to set each language string with a foreach setting english/german texts. But this did not work out, because i somehow mixed up setting the view correctly.
To make it short:
Creating categories and subcategories like this does work very good, but i do not get it to work to pass english/german categoty titles.
Thanks guys
For all of you who are struggeling with this situation i made a workaound like this:
I added all those values to the affected database tables directly. This is for sure a quick and dirty way, but it does the job.
For all in need of some ideas here is the (undocumented) snipped belonging to my initial post.
// Get values for next language insert
$entity_type_id = $category
->getResource()
->getTypeId();
$entity_id = $category->getEntityId();
$read_entity = Mage::getSingleton('core/resource')
->getConnection('core_write');
$sql_entity = "SELECT * FROM eav_attribute WHERE
`attribute_code` = 'name' AND
`entity_type_id` = " . $entity_type_id . ";";
$row_entity = $read_entity
->fetchRow($sql_entity);
$attribute_id = $row_entity['attribute_id'];
// prepare value for name field in different langauge
$val = Mage::getSingleton('core/resource')
->getConnection('default_write')
->quote($v['en']);
$sql_insert = "INSERT INTO `catalog_category_entity_varchar`
(`entity_type_id`,`attribute_id`,`store_id`,`entity_id`,`value`)
VALUES ($entity_type_id,$attribute_id,$storeId,$entity_id,$val);";
$read_entity->query($sql_insert);
I hope this helps someone out who is in need of this.

Resources