I want to know how to use transaction query to rollback if my queries have errors and commit if not. I have queries that use foreach cause of having multiple data. here's what I'm trying.
DB::transaction(function(){
$receiving = New Table1;
$receiving->created_on = \Carbon\Carbon::now();
$receiving->created_by = Auth::user()->id;
$receiving->received_on = \Carbon\Carbon::parse($request->DateAcquired);
$receiving->received_by = Auth::user()->id;
$receiving->checked_on = \Carbon\Carbon::now();
$receiving->checked_by = Auth::user()->id;
$receiving->remark = $request->Remarks;
$receiving->save();
foreach ($request->data as $data)
{
$asset = New Table2;
$asset->category = $data[0];
/*$asset->asset_number = $data[1];*/
$asset->name = $data[2];
$asset->brand = $data[3];
$asset->model = $data[4];
$asset->ownership_type = $data[5];
$asset->serial_number = $data[6];
$asset->mac_address = $data[7];
$asset->cpu = $data[8];
$asset->memory = $data[9];
$asset->hard_disk = $data[10];
$asset->os = $data[11];
$asset->remark = $data[12];
$asset->description = $data[13];
$asset->date_acquired = \Carbon\Carbon::parse($request->DateAcquired);
$asset->receiving_id = $receiving->id;
$asset->save();
}
});
I also tried using DB::beginTransaction();
but I'm getting an error of
undefined beginTransaction() function in query builder.
As mentioned in Laravel Database Transactions:
You may use the transaction method on the DB facade to run a set of
operations within a database transaction. If an exception is thrown
within the transaction Closure, the transaction will automatically be
rolled back. If the Closure executes successfully, the transaction
will automatically be committed. You don't need to worry about
manually rolling back or committing while using the transaction
method:
but as I can see in your code that you are using $request variable within the callback function of transaction, so at this point, you should pass the $request to the callback function to use it.
your code will like below:
DB::transaction(function() use ($request) {
// put your code here
});
You may need to pass your variable to the transaction via use()
DB::transaction(function() use ($request) {
$receiving = New Table1;
$receiving->created_on = \Carbon\Carbon::now();
$receiving->created_by = Auth::user()->id;
$receiving->received_on = \Carbon\Carbon::parse($request->DateAcquired);
$receiving->received_by = Auth::user()->id;
$receiving->checked_on = \Carbon\Carbon::now();
$receiving->checked_by = Auth::user()->id;
$receiving->remark = $request->Remarks;
$receiving->save();
foreach ($request->data as $data)
{
$asset = New Table2;
$asset->category = $data[0];
/*$asset->asset_number = $data[1];*/
$asset->name = $data[2];
$asset->brand = $data[3];
$asset->model = $data[4];
$asset->ownership_type = $data[5];
$asset->serial_number = $data[6];
$asset->mac_address = $data[7];
$asset->cpu = $data[8];
$asset->memory = $data[9];
$asset->hard_disk = $data[10];
$asset->os = $data[11];
$asset->remark = $data[12];
$asset->description = $data[13];
$asset->date_acquired = \Carbon\Carbon::parse($request->DateAcquired);
$asset->receiving_id = $receiving->id;
$asset->save();
}
});
Related
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
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', 'შეკვეთა წარმატებით დაემატა');
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();
}
}
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();
}
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..