How to connect controller eloquent's - laravel

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', 'შეკვეთა წარმატებით დაემატა');

Related

Laravel | Update two tables

I have a doubt here regarding changing data in two tables in
public function editar_perfil(Request $request, funcionario $item){
$item->nome = $request->nome;
$item->email = $request->email;
$item->telefone = $request->telefone;
//$item->foto = $request->foto;
$item->data_nasc = $request->data_nasc;
$item->nacionalidade = $request->nacionalidade;
$item->n_cartao_cc = $request->n_cartao_cc;
$item->nif = $request->nif;
$item->morada = $request->morada;
$item->n_porta = $request->n_porta;
$item->localidade = $request->localidade;
$item->concelho = $request->concelho;
$item->distrito = $request->distrito;
$item->cp = $request->cp;
$item->data_entrada = $request->data_entrada;
$item->funcao = $request->funcao;
$item->estado = $request->estado;
//$item->n_ferias_disponiveis = $request->n_ferias_disponiveis;
//$item->data_registo = $now;
$item->save();
What I want to do now is that the line
$item->n_ferias_disponiveis = $request->n_ferias_disponiveis;
Be changed in another 'Ferias' table
Is there a way to do it directly? Thank you!
EDIT:
I store the data as follows:
$tabela->nome = $request->nome;
$tabela->email = $request->email;
$tabela->telefone = $request->telefone;
(...)
$result = $tabela->save();
$tabela4 = new feria();
$tabela4->id_funcionario = $tabela->id;
$tabela4->n_ferias_disponiveis = $request->n_ferias_disponiveis;
$tabela4->save();
And now I want to edit these same tables.
I think if there is relationship between the two tables it will change automatically

DRY Coding in Laravel 7+

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

I want to reduce my stock when bill is generated/saved

I am using this method to save customer data and sales as per ID. Now i want to reduce my stock when bill is saved or generated.
public function addBill(Request $request)
{
// $this->validate($request,[
// 'cus_id'=>'required'
// ]);
$customer = new Customer;
$customer->cus_id_no = $request->cus_id_no;
$customer->name = $request->name;
$customer->p_number = $request->p_number;
$customer->address = $request->address;
$customer->cus_type = $request->cus_type;
$customer->total = $request->total;
$customer->tax = $request->tax;
$customer->g_total = $request->g_total;
$customer->paid = $request->paid;
$customer->remaining = $request->g_total - $request->paid;
if($customer->save()){
$id=$customer->id;
foreach($request->productname as $key=>$v)
{
$data = array('cus_id'=>$id,
'pro_id'=>$v,
'actual_cost'=>$request->actual_cost[$key],
'qty'=>$request->qty[$key],
'price'=>$request->price[$key],
'dis'=>$request->dis[$key],
'amount'=>$request->amount[$key]
);
Sale::insert($data);
}
}
}
Stock is my Model name and stocks is my table name.

Laravel 5.5 Data is being inserted twice in database

This code enters multiple products in orders table, but what strange thing is happening is if i insert 2 products, data is being entered 4 times, if i insert 1 product it is being inerted 2 times. What is wrong with this code ?
foreach($request->product_id as $rpk => $rpv)
{
$data = new Order();
$data->user_id = $request->customer_id[$rpk];
$data->status = $request->status[$rpk];
$data->save();
Order::where('id', $data->id)->update(['order_number' => $data->id]);
// For OrderDetail
$detail = new OrderDetail();
$detail->customer_id = $request->customer_id[$rpk];
$detail->order_id = $data->id;
$detail->product_id = $request->product_id[$rpk];
$detail->price = $request->price[$rpk];
$detail->quantity = $request->quantity[$rpk];
$detail->total = $request->total[$rpk];
$detail->comment = $request->comment[0];
$detail->date = date('Y-m-d H:i:s');
$detail->bill_date = date('Y-m-d H:i:s');
//$detail->sales_tax = '13'; // Need to change this
$success = $detail->save();
}

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

Resources