DRY Coding in Laravel 7+ - laravel

I have been using Laravel as a beginner for a few weeks now and i am seeking for knowledge.
I hope that you can help me!
I would like to clean up my project and its controllers.
I have two api refresh buttons which retrieves new orders and updates existing orders from an api.
One button is for a specific costcentre and the other button is for refreshing all orders at the same time.
Not to forget, it also updates the OrderProduct rows.
For this i have used the same code with just a little difference for each function.
While i like to not repeat the same.
Is there any solution for this?
Example current situation:
Specific costcentre
$order = new Order();
$order->costcentre_id = $costcentre->id;
$order->invoice = $row['invoice_prefix'] . $row['invoice_no'];
$order->customer_id = $row['customer_id'];
$order->firstname = $row['firstname'];
$order->lastname = $row['lastname'];
$order->email = $row['email'];
$order->telephone = $row['telephone'];
$order->save();
foreach ($product as $prod) {
$newprod = new Product();
$newprod->name = $prod->name;
$newprod->save();
}
All costcentres
foreach ($costcentre as $cc) {
$order = new Order();
$order->costcentre_id = $cc->id;
$order->invoice = $row['invoice_prefix'] . $row['invoice_no'];
$order->customer_id = $row['customer_id'];
$order->firstname = $row['firstname'];
$order->lastname = $row['lastname'];
$order->email = $row['email'];
$order->telephone = $row['telephone'];
$order->save();
foreach ($product as $prod) {
$newprod = new Product();
$newprod->name = $prod->name;
$newprod->save();
}
}

Related

How to connect controller eloquent's

I don't know if my question title is correct but I will try to form the question here correctly.
So I am creating order and customer management system in laravel and I am struggling with connecting two tables and controllers with each other.
I have two tables:
orders table with one test record
customers table with one test record
Also I have controller "OrdersController" with store function here is a source code:
public function store(Request $request)
{
$this->validate($request, [
'customer'=>'required',
'date'=>'required',
'products'=>'required',
'phone'=>'required',
'country'=>'required',
'state'=>'required',
'city'=>'required',
'address1'=>'required',
'address2'=>'required',
'zip'=>'required',
'sold_price'=>'required',
'gross_price'=>'required',
'paypal_fee'=>'required',
'track_number'=>'required',
'track_price'=>'required',
'track_link'=>'required',
'currency'=>'required'
]);
$order = new Order;
$order->customer = $request->input('customer');
$order->date = $request->input('date');
$order->products = $request->input('products');
$order->phone = $request->input('phone');
$order->country = $request->input('country');
$order->state = $request->input('state');
$order->city = $request->input('city');
$order->address1 = $request->input('address1');
$order->address2 = $request->input('address2');
$order->zip = $request->input('zip');
$order->sold_price = $request->input('sold_price');
$order->gross_price = $request->input('gross_price');
$order->paypal_fee = $request->input('paypal_fee');
$order->track_number = $request->input('track_number');
$order->track_price = $request->input('track_price');
$order->track_link = $request->input('track_link');
$order->currency = $request->input('currency');
$order->save();
return redirect('/orders')->with('success', 'შეკვეთა წარმატებით დაემატა');
}
So I want to check if record with $order->phone exists in customers table, if it exists don't create new record in customers table, and if it not exists I want to create new record in customers table with $order->customer (customer's name) and $order->phone (customer's phone).
This is my questions, I am a beginner and this is my first project, if here is some fatal mistakes please tell me. Thank you in advance!
First check in customer table with phone number record exist or not like this. I assume that your customer model is Customer
$customer = Customer::where('phone', '=', $request->input('phone'))->first();
if(!$customer){
create Customer here
}
$order = new Order;
$order->customer = $request->input('customer');
$order->date = $request->input('date');
$order->products = $request->input('products');
$order->phone = $request->input('phone');
$order->country = $request->input('country');
$order->state = $request->input('state');
$order->city = $request->input('city');
$order->address1 = $request->input('address1');
$order->address2 = $request->input('address2');
$order->zip = $request->input('zip');
$order->sold_price = $request->input('sold_price');
$order->gross_price = $request->input('gross_price');
$order->paypal_fee = $request->input('paypal_fee');
$order->track_number = $request->input('track_number');
$order->track_price = $request->input('track_price');
$order->track_link = $request->input('track_link');
$order->currency = $request->input('currency');
$order->save();
return redirect('/orders')->with('success', 'შეკვეთა წარმატებით დაემატა');

Access the cart session - Laravel 5.8

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);
}

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..

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..
}
}

Magento - How can I add rating information to a review

I'm manually creating reviews in Magento and I'm trying to find out how I add the rating information in? I can add the reviews no problem but I'm struggling with the rating values (star values).
I have an array that looks like this:
array("Price"=>80, "Value"=>60, "Quality"=>60);
How can I add that to the star system and the Summary Rating?
Thanks.
Ok, so this is what I have so far:
This adds a review:
$review->setEntityPkValue(23);//product id
$review->setStatusId(1);
$review->setTitle("title");
$review->setDetail("detail");
$review->setEntityId($review->getEntityIdByCode(Mage_Review_Model_Review::ENTITY_PRODUCT_CODE));
$review->setStoreId(Mage::app()->getStore()->getId());
$review->setStatusId(1); //approved
$review->setNickname("Me");
$review->setReviewId($review->getId());
$review->setStores(array(Mage::app()->getStore()->getId()));
$review->save();
$review->aggregate();
This adds a rating for a review <-I'm stuck here!
// this is some test code to add the rating review
$rating[0]['Price'] = 80;
$rating[0]['Value'] = 100;
$rating[0]['Quality'] = 80;
$product_id = 23;
$review_id = 631;
foreach ($rating as $ratingId => $optionId) {
// This is the bit where it all seems to go wrong!:
Mage::getModel('rating/rating')
->setRatingId(1)
->setReviewId($review_id)
->addOptionVote($val, $product_id);
}
Thanks!
This worked for me:
public function addReview($ratingarray)
{
$product_id = $ratingarray['product_id'];
$storeid = $ratingarray['store_id'];
$title = $ratingarray['title'];
$customerid = $ratingarray['customer_id'];
$nickname = $ratingarray['nickname'];
$detail = $ratingarray['detail'];
$review = Mage::getModel('review/review');
$review->setEntityPkValue($product_id);
$review->setStatusId(1);
$review->setTitle($title);
$review->setDetail($detail );
$review->setEntityId($review->getEntityIdByCode(Mage_Review_Model_Review::ENTITY_PRODUCT_CODE));
$review->setStoreId($storeid);
$review->setStatusId(1); //approved
$review->setCustomerId($customerid);
$review->setNickname($nickname);
$review->setReviewId($review->getId());
$review->setStores(array($storeid));
$review->save();
$review->aggregate();
//return "success";
$rating_options = $ratingarray['options'];
/*array(
array(1,2,3,4),
array(6,7,8),
array(11,12)
);*/
$row = count($rating_options);
$rating_id = 1;
foreach($rating_options as $key1=>$val1)
{
foreach($val1 as $key2=>$val2)
{
$_rating = Mage::getModel('rating/rating')
->setRatingId($key1)
->setReviewId($review->getId())
->addOptionVote($val2,$product_id );
}
}
return "Success";
}
I am calling this like =>
$options = array(1=>array(1,2,3,4),2=>array(6,7,8),3=>array(11,12));
$reviewarray = array('customer_id'=>'21','product_id'=>'176','store_id'=>'4','title'=>'Review','nickname'=>'XYZ','detail'=>'Nice Product with Life time warrenty', 'options'=>$options);

Resources