Getting data into array - laravel

I'm working on some e-commerce website based on merchant. There is problem comping in submitting order. the problem is when i'm selecting same merchant that time order will be stored successfully, but when i'm selecting multiple product from different merchant that time my function through error of Undefined offset:1. Here is my function.
public function post_order(){
$data = Input::all();
$count = count($data['invoice_no']);
$order = array();
for($i=0; $i<$count; $i++){
if(!empty($data['invoice_no'][$i])){
array_push($order, array(
'order_no' => $data['order_no'][$i],
'invoice_prefix' => $data['invoice_prefix'][$i],
'invoice_no' => $data['invoice_no'][$i],
'merchant_id' => $data['merchant_id'][$i],
'customer_id' => $data['customer_id'][$i],
'buytokri_order' => $data['order_name'][$i],
'name' => $data['name'][$i],
'pincode' => $data['pincode'][$i],
'address' => $data['address'][$i],
'landmark' => $data['landmark'][$i],
'city' => $data['city'][$i],
'state' => $data['state'][$i],
'country' => $data['country'][$i],
'mobile' => $data['mobile'][$i],
'subtotal' => $data['selling_price'][$i],
'payment_type' => $data['payment_type'][$i],
'txn_id' => $data['txn'][$i],
'shipping' => $data['shipping'][$i],
'total' => $data['subtotal'][$i]
));
}
}
Order::insert($order);
$var = $data['order_no'];
foreach ($var as $vars) {
$id = DB::table('ads_order')->where('order_no', $vars)->get();
}
$count = count($data['invoice_no']);
$orderhistory = array();
for($i=0; $i<=$count; $i++){
if(!empty($data['invoice_no'][$i])){
array_push($orderhistory, array(
'order_id' => $id[$i]->id,
'merchant_id' => $data['merchant_id'][$i],
'customer_id' => $data['customer_id'][$i],
'order_status' => $data['order_status'][$i],
'comment' => $data['comment'][$i],
'notify' => $data['notify'][$i],
'default' => $data['default'][$i],
'status' => $data['status'][$i]
));
}
}
Orderhistory::insert($orderhistory);
return Redirect::intended('/ordersuccess');
}

Related

I cant get lastInsertId on laravel 7 project

$sql = DB::table('laravel_products')
->insert(array(
'name' => $name,
'price' => $price,
'qty' => $qty,
'description' => $description,
'uruu' => $uruu,
'garage' => $garage,
'duureg' => $duureg,
'tagt' => $tagt,
'talbai' => $talbai,
'haalga' => $haalga,
'tsonh' => $tsonh,
'shal' => $shal,
'tsonhtoo' => $ttsonh,
'hdawhar' => $bdawhar,
'lizing' => $lizing,
'utas' => $utas,
'email' => $email,
'hereg' => $hereg,
'bairshil' => $bairshil,
'bairlal' => $bairlal,
'ashig' => $ashigon,
'zahi' => $zahi,
'image' => $data
));
$lastInsertedID = $sql->lastInsertId();
When I try to insert its responses:
"Call to a member function lastInsertId() on bool"
I used insertGetId but its cant save multiple rows of pictures on mysql.
If you want to get the last inserted ID like that you can call that method on the PDO instance directly:
$id = DB::getPdo()->lastInsertId();
If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:
$id = DB::table('users')->insertGetId(
['email' => 'john#example.com', 'votes' => 0]
);
from : https://laravel.com/docs/5.8/queries#inserts
$data = new LaravelProducts(); //LaravelProducts is your Model Name
$data->name= $name; //here 'name' is your column name
$data->price= $price; //here 'price' is your column name
$data->qty= $qty; //here 'qty' is your column name
$data->description= $description; //here 'description' is your column name
..........
..........
$data->image= $image; //here 'image' is your column name
$data->save();
$lastInsertedId = $data->id;
You don't have to write a new query to collect last inserted id from database.
$laravel_product = DB::table('laravel_products')
->insertGetId( array(
'name' => $name,
'price' => $price,
'qty' => $qty,
'description' => $description,
'uruu' => $uruu,
'garage' => $garage,
'duureg' => $duureg,
'tagt' => $tagt,
'talbai' => $talbai,
'haalga' => $haalga,
'tsonh' => $tsonh,
'shal' => $shal,
'tsonhtoo' => $ttsonh,
'hdawhar' => $bdawhar,
'lizing' => $lizing,
'utas' => $utas,
'email' => $email,
'hereg' => $hereg,
'bairshil' => $bairshil,
'bairlal' => $bairlal,
'ashig' => $ashigon,
'zahi' => $zahi,
'image' => $data
)
);
foreach ($filenamesToSave as $filename) {
DB::insert('INSERT INTO laravel_products_images ( product_id, filename ) VALUES ( ?, ? )',[$laravel_product->id, $filename]);
return view('createproduct');
} // Foreach Closing
// Echo your inserted ID Like Below
echo $laravel_product->id;
It should be 100% working for you.

How to update data in database using import excel laravel if any data exist

how to update data in database with import excel if data exist just update, and if not exist just save. i am using laravel 5.8 and maatwebsite 2.1
this is my controller :
$request->validate([
'file' => 'required|mimes:csv,xls,xlsx',
'divisi' => 'required',
'file_type' => 'required'
]);
$path = $request->file('file')->getRealPath();
$data = Excel::load($path)->first();
$divisi = $request->input('divisi');
$file_type = $request->input('file_type');
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$arr[] = [
'product_id' => $value->product_id,
'upc' => $value->upc,
'desc_a' => $value->desc_a,
'name' => $value->name,
'category' => $value->category,
'desc_b' => $value->desc_b,
'desc_c' => $value->desc_c,
'desc_d' => $value->desc_d,
'desc_e' => $value->desc_e,
'desc_f' => $value->desc_f,
'desc_g' => $value->desc_g,
'desc_h' => $value->desc_h,
'fixel_id' => $value->fixel_id,
'x' => $value->x,
'cost' => $value->cost,
'price' => $value->price,
'reg_movement' => $value->reg_movement,
'total_facings' => $value->total_facings,
'total_units' => $value->total_units,
'days_of_supply' => $value->days_of_supply,
'desc_i' => $value->desc_i,
'kode_lokasi' => $value->kode_lokasi,
'created_by' => Auth::user()->id,
'updated_by' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
'divisi' => $divisi,
'file_type' => $file_type];
}
if(!empty($arr)){
Planogram::updateOrCreate($arr);
} }
from this code my data always multiply with same record.
thank you
Done, just change to this
if($data->count()){
foreach ($data as $key => $value) {
$getsku = PlanogramTemp::updateOrCreate([
'desc_b' => $value->desc_b,
'desc_e' => $value->desc_e
],[
'product_id' => $value->product_id,
'upc' => $value->upc,
'desc_a' => $value->desc_a,
'name' => $value->name,
'category' => $value->category,
'desc_b' => $value->desc_b,
'desc_c' => $value->desc_c,
'desc_d' => $value->desc_d,
'desc_e' => $value->desc_e,
'desc_f' => $value->desc_f,
'desc_g' => $value->desc_g,
'desc_h' => $value->desc_h,
'fixel_id' => $value->fixel_id,
'x' => $value->x,
'cost' => $value->cost,
'price' => $value->price,
'reg_movement' => $value->reg_movement,
'total_facings' => $value->total_facings,
'total_units' => $value->total_units,
'days_of_supply' => $value->days_of_supply,
'desc_i' => $value->desc_i,
'kode_lokasi' => $value->kode_lokasi,
'created_by' => Auth::user()->id,
'updated_by' => Auth::user()->id,
'divisi' => $divisi,
'file_type' => $file_type]);
}

Insert data in 2 tables with the last inserted ID of the parent table must also be inserted in the child table

I tried with the code below. The record is inserted but the parent ID is not.
The last inserted ID of the parent table must also be inserted in the child table the same time when submit button is clicked.
Thanks.
Controller:
public function insert_doc_control_review(Request $request)
{
$form_data = array(
'comment' => $request->comment,
'assigned_to' => $request->assigned_to,
'revision' => $request->revision,
'file_id' => $request->file_id,
'attachment' => $request->attachment,
'phase_id' => $request->phase_id,
'review_date' => $request->review_date,
'due_date' => $request->due_date,
'completed_date' => $request->completed_date,
'user_id' => Auth::user()->id,
'doc_number' => $this->getNextDocRevNumber()
);
DocumentControlReview::create($form_data);
$lastId = DocumentControlReview::create($form_data);
$archive_data = array(
'user_id' => Auth::user()->id,
'iso_management_id' => $request->iso_management_id,
'phase_id' => $request->phase_id,
'document_control_review_id' => $request->document_control_review_id,
'initial_approval_id' => $request->initial_approval_id,
'review_id' => $request->review_id,
'final_approval_id' => $request->final_approval_id,
'awaiting_release_id' => $request->awaiting_release_id,
'release_id' => $request->release_id,
'project_id' => $request->project_id,
'folder_id' => $request->folder_id,
'file_id' => $request->file_id,
$lastId
);
DocumentRecordArchive::create($archive_data);
}
You have to write the code like below.
public function insert_doc_control_review(Request $request)
{
$form_data = array(
'comment' => $request->comment,
'assigned_to' => $request->assigned_to,
'revision' => $request->revision,
'file_id' => $request->file_id,
'attachment' => $request->attachment,
'phase_id' => $request->phase_id,
'review_date' => $request->review_date,
'due_date' => $request->due_date,
'completed_date' => $request->completed_date,
'user_id' => Auth::user()->id,
'doc_number' => $this->getNextDocRevNumber()
);
$lastId = DocumentControlReview::create($form_data);
$archive_data = array(
'user_id' => Auth::user()->id,
'iso_management_id' => $request->iso_management_id,
'phase_id' => $request->phase_id,
'document_control_review_id' => $lastId->id, // Parent ID
'initial_approval_id' => $request->initial_approval_id,
'review_id' => $request->review_id,
'final_approval_id' => $request->final_approval_id,
'awaiting_release_id' => $request->awaiting_release_id,
'release_id' => $request->release_id,
'project_id' => $request->project_id,
'folder_id' => $request->folder_id,
'file_id' => $request->file_id,
//'parent_id' => $lastId->id, there is document_control_review_id which I assume is the parent_id foreign column.
);
DocumentRecordArchive::create($archive_data);
}
look lastId is an object which holds the newly created data. you want to add this one's id in the child table. so use it's id attribute. i used parent_id as column name, change it according to your column name.
In case you have well formed relations in both models, another way can be:
$formData = [
'comment' => $request->comment,
'assigned_to' => $request->assigned_to,
'revision' => $request->revision,
'file_id' => $request->file_id,
'attachment' => $request->attachment,
'phase_id' => $request->phase_id,
'review_date' => $request->review_date,
'due_date' => $request->due_date,
'completed_date' => $request->completed_date,
'user_id' => Auth::id(),
'doc_number' => $this->getNextDocRevNumber(),
];
$documentControlReview = DocumentControlReview::create($formData);
$archiveData = [
'user_id' => Auth::id(),
'iso_management_id' => $request->iso_management_id,
'phase_id' => $request->phase_id,
'document_control_review_id' => $request->document_control_review_id,
'initial_approval_id' => $request->initial_approval_id,
'review_id' => $request->review_id,
'final_approval_id' => $request->final_approval_id,
'awaiting_release_id' => $request->awaiting_release_id,
'release_id' => $request->release_id,
'project_id' => $request->project_id,
'folder_id' => $request->folder_id,
'file_id' => $request->file_id,
];
$documentControlReview->documentRecordArchive()->create(archiveData);
For this working you need to have:
// DocumentControlReview::class
public function documentRecordArchive
{
return $this->hasOne(DocumentRecordArchive::class, 'parent_id');
}
// or
public function documentRecordArchives
{
return $this->hasMany(DocumentRecordArchive::class, 'parent_id');
}
// one of these two regarding which relation is set in business model 1:n or m:n
// DocumentRecordArchive::class
public function documentControlReview()
{
return $this->belongsTo(DocumentControlReview::class, 'parent_id');
}
Also, if child record in DB is mandatory, it is smart to set all transactions into try catch block:
try {
\DB::beginTransaction();
// make parent insertion
// make child insertion
// make another related DB actions if needed
// all good
\DB::commit();
} catch (\Exception $e) {
// nothing will be applied, something went wrong with one DB transaction
\DB::rollback();
// return redirect()->back()->with('error', $e->getMessage());
}
What is main thing I want to point here is that you don't need to use parentId value in array of child's data because it will be recognised as well and it is in some hand more secure - there is no way wrong parentId would be applied.
$firstTransaction->relationFromModel()->create($dataWithoutFirstTransactionIdBecauseItIsAlreadyAppliedThisWay);
Try this
public function insert_doc_control_review(Request $request)
{
$form_data = array(
'comment' => $request->comment,
'assigned_to' => $request->assigned_to,
'revision' => $request->revision,
'file_id' => $request->file_id,
'attachment' => $request->attachment,
'phase_id' => $request->phase_id,
'review_date' => $request->review_date,
'due_date' => $request->due_date,
'completed_date' => $request->completed_date,
'user_id' => Auth::user()->id,
'doc_number' => $this->getNextDocRevNumber()
);
$lastId = DocumentControlReview::create($form_data);
$archive_data = array(
'user_id' => Auth::user()->id,
'iso_management_id' => $request->iso_management_id,
'phase_id' => $request->phase_id,
'initial_approval_id' => $request->initial_approval_id,
'review_id' => $request->review_id,
'final_approval_id' => $request->final_approval_id,
'awaiting_release_id' => $request->awaiting_release_id,
'release_id' => $request->release_id,
'project_id' => $request->project_id,
'folder_id' => $request->folder_id,
'file_id' => $request->file_id,
'document_control_review_id' => $lastId->id
);
DocumentRecordArchive::create($archive_data);
}

Importing excel has an error of "Illegal string offset" in my controller

I'm trying to import an excel to my database table 'users' but it has an error saying Illegal string offset "email". I tried deleting the "email" then it says that Illegal string offset "username" now. Is it really the error in controller? Or maybe the reason is that i also have a repository.
This is my code for the controller
public function userImport()
{
if( Input::file('file_import') ) {
$path = Input::file('file_import')->getRealPath();
$inserts = [];
Excel::load($path,function($reader) use (&$inserts)
{
foreach ($reader->toArray() as $rows){
foreach($rows as $row){
$inserts[] = ['email' => $row['email'], 'username' => $row
['username'], 'password' => $row['password'], 'first_name' => $row['first_name'],'middle_name' => $row['middle_name'], 'last_name' => $row['last_name'], 'gender' => $row['gender'],
'civil_status' => $row['civil_status'], 'spouse' => $row['spouse'], 'religion' => $row['religion'],'emergency_no' => $row['emergency_no'],'previous_work' => $row['previous_work'],
'remarks' => $row['remarks'],'course' => $row['course'],'biometrics' => $row['biometrics'],'immediate_head' => $row['immediate_head'],'designation' => $row['designation'],'level' => $row['level'],
'emp_status' => $row['emp_status'],'dependents' => $row['dependents'],'date_hired' => $row['date_hired'],'regularization_date' => $row['regularization_date'],'remmitance_date' => $row['remmitance_date'],
'tin' => $row['tin'],'philhealth' => $row['philhealth'],'pagibig' => $row['pagibig'],'sss' => $row['sss'],'umid' => $row['umid'],'phone' => $row['phone'],'avatar' => $row['avatar'],
'address' => $row['address'],'country_id' => $row['country_id'],'role_id' => $row['role_id'],'birthday' => $row['birthday'],'status' => $row['status']];
}
}
});
}
if (!empty($inserts)) {
DB::table('users')->insert($inserts);
return back()->with('success','Inserted Record successfully');
}
return back();
}
As per your dumped $rows, it looks like that you don't need another foreach inside another foreach, modify your code.
// readability purpose
$rows = $reader->toArray();
foreach ($rows as $row){
$inserts[] = ['email' => $row['email'], 'username' => $row
['username'], 'password' => $row['password'], 'first_name' => $row['first_name'],'middle_name' => $row['middle_name'], 'last_name' => $row['last_name'], 'gender' => $row['gender'],
'civil_status' => $row['civil_status'], 'spouse' => $row['spouse'], 'religion' => $row['religion'],'emergency_no' => $row['emergency_no'],'previous_work' => $row['previous_work'],
'remarks' => $row['remarks'],'course' => $row['course'],'biometrics' => $row['biometrics'],'immediate_head' => $row['immediate_head'],'designation' => $row['designation'],'level' => $row['level'],
'emp_status' => $row['emp_status'],'dependents' => $row['dependents'],'date_hired' => $row['date_hired'],'regularization_date' => $row['regularization_date'],'remmitance_date' => $row['remmitance_date'],
'tin' => $row['tin'],'philhealth' => $row['philhealth'],'pagibig' => $row['pagibig'],'sss' => $row['sss'],'umid' => $row['umid'],'phone' => $row['phone'],'avatar' => $row['avatar'],
'address' => $row['address'],'country_id' => $row['country_id'],'role_id' => $row['role_id'],'birthday' => $row['birthday'],'status' => $row['status']];
}
$rows already represents each row, so you should probably rename it to $row.

Decrease product quantity in database after checkout

I have cart on my web store and so far everything works perfectly but I said when I try decrement the product quantity to product, the all product in my database will decrement Not just products in cart.
Here is my ordercontroller :
public function postOrder(Request $request) {
$validator = Validator::make($request->all(), [
'first_name' => 'required|max:30|min:2',
'last_name' => 'required|max:30|min:2',
'address' => 'required|max:50|min:4',
'address_2' => 'max:50|min:4',
'city' => 'required|max:50|min:3',
'state' => 'required|',
'zip' => 'required|max:11|min:4',
'full_name' => 'required|max:30|min:2',
]);
if ($validator->fails()) {
return redirect('/checkout')
->withErrors($validator)
->withInput();
}
$first_name = Input::get('first_name');
$last_name = Input::get('last_name');
$address = Input::get('address');
$address_2 = Input::get('address_2');
$city = Input::get('city');
$state = Input::get('state');
$zip = Input::get('zip');
$full_name = Input::get('full_name');
$user_id = Auth::user()->id;
$cart_products = Cart::with('products')->where('user_id', '=', $user_id)->get();
$cart_total = Cart::with('products')->where('user_id', '=', $user_id)->sum('total')
$charge_amount = number_format($cart_total, 2) * 100;
$order = Order::create (
array(
'user_id' => $user_id,
'first_name' => $first_name,
'last_name' => $last_name,
'address' => $address,
'address_2' => $address_2,
'city' => $city,
'state' => $state,
'zip' => $zip,
'total' => $cart_total,
'full_name' => $full_name,
));
foreach ($cart_products as $order_products) {
$order->orderItems()->attach($order_products->product_id, array(
'qty' => $order_products->qty,
'price' => $order_products->products->price,
'reduced_price' => $order_products->products->reduced_price,
'total' => $order_products->products->price * $order_products->qty,
'total_reduced' => $order_products->products->reduced_price * $order_products->qty,
));
}
// in the fact all product will decrement Not just products in cart
\DB::table('products')->decrement('product_qty', $order_products->qty);
Cart::where('user_id', '=', $user_id)->delete();
flash()->success('Success', 'Your order was processed successfully.');
return redirect()->route('cart');
}
I use program \DB::table('products')->decrement('product_qty', $order_products->qty);; for the decrement but in the fact all product will decrement Not just products in cart
The decrement you are using updates all records, as you have observed because you didn't constrain it to a specific record. You want to do this in your loop:
DB::table('products')
->where('id', '=', $order_products->product_id)
->decrement('product_qty', $order_products->qty);

Resources