Laravel: How to insert multiple records - laravel

I want to insert multiple records in my database using Laravel, however when i insert it, it only gives me one record in the database
Here's my Controller
public function postCreateAttendance()
{
$validate = Validator::make(Input::all(), array(
'status' => 'required'
));
if ($validate->fails())
{
return Redirect::route('viewStudent')->withErrors($validate)->withInput();
}
else
{
foreach(User::all() as $user):
foreach(User::whereRaw('isTeacher = "0" and isAdmin = "0"')->get() as $student)
foreach(User::whereRaw('isTeacher = "1" and isAdmin = "0"')->get() as $teacher)
//$users[$user->id]=$user->firstname;
$attendance = new Attendance();
$attendance->status = Input::get('status');
$attendance->comment = Input::get('comment');
$attendance->student_id = $student->id=$student->id;
$attendance->student_firstname = $student->id=$student->firstname;
$attendance->student_lastname = $student->id=$student->lastname;
$attendance->teacher_id = $teacher->id=$teacher->id;
$attendance->teacher_firstname = $teacher->id=$teacher->firstname;
$attendance->teacher_lastname = $teacher->id=$teacher->lastname;
if($attendance->save())
{
return Redirect::route('viewStudent')->with('success', 'ATTENDANCE HAS BEEN RECORDED!');
}
else
{
return Redirect::route('viewStudent')->with('fail', 'An error occured while creating the attendance.');
}
endforeach;
}
}
How can i save multiple records? Please help Thank You ^_^

The issue is that you are returning during the foreach loop - so only one record is processed. You need to process all the records, then return the route.
Here is some refactoring of your code
public function postCreateAttendance()
{
$validate = Validator::make(Input::all(), array(
'status' => 'required'
));
if ($validate->fails()) {
return Redirect::route('viewStudent')->withErrors($validate)->withInput();
}
foreach(User::where('isTeacher', '0')->where('isAdmin', '0')->get() as $student) {
foreach(User::where('isTeacher', '1')->where('isAdmin', '0')->get() as $teacher) {
$attendance = new Attendance();
$attendance->status = Input::get('status');
$attendance->comment = Input::get('comment');
$attendance->student_id = $student->id;
$attendance->student_firstname = $student->firstname;
$attendance->student_lastname = $student->lastname;
$attendance->teacher_id = $teacher->id;
$attendance->teacher_firstname = $teacher->firstname;
$attendance->teacher_lastname = $teacher->lastname;
$attendance->save();
}
}
return Redirect::route('viewStudent')->with('success', 'ATTENDANCE HAS BEEN RECORDED!');
}
Edit: I've removed the first foreach(User::all() as $user): - because at the moment, in your code, it does nothing...?

Related

laravel excel import update only if there is a change

i have laravel excel maatwebsite import update function, it works really well but i want to mark record that change by add "correction_flag" variable. the question is, how can i set this "correction_flag" when import.
this is my import function:
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
$tgl_lahir_cell = $this->transformDate($row['tanggal_lahir']);
$tgl_awal_masa_kerja_cell = $this->transformDate($row['tanggal_awal_masa_kerja']);
$tgl_menjadi_permanen_cell = $this->transformDate($row['tanggal_menjadi_permanen']);
$tgl_keluar_cell = $this->transformDate($row['tanggal_keluar']);
if($tgl_lahir_cell == '1970-01-01') {
$formatedDate1 = NULL;
}else{
$formatedDate1 = $tgl_lahir_cell;
}
if($tgl_awal_masa_kerja_cell == '1970-01-01') {
$formatedDate2 = NULL;
}else{
$formatedDate2 = $tgl_awal_masa_kerja_cell;
}
if($tgl_menjadi_permanen_cell == '1970-01-01') {
$formatedDate3 = NULL;
}else{
$formatedDate3 = $tgl_menjadi_permanen_cell;
}
if($tgl_keluar_cell == '1970-01-01') {
$formatedDate4 = NULL;
}else{
$formatedDate4 = $tgl_keluar_cell;
}
Tempdat::where('cc', Auth::user()->ccode)
->where('id_tempdat', $row['id_tempdat'])
->update([
'golongan' => $row['golongan'],
'nama' => $row['nama'],
'jenis_kelamin' => $row['jenis_kelamin'],
'tgl_lahir' => $formatedDate1,
'tgl_awal_masa_kerja' => $formatedDate2,
'tgl_menjadi_permanen' => $formatedDate3,
'status_awal' => $row['status_di_awal_periode'],
'gaji_pokok_awal' => $row['gaji_pokok_di_awal_periode'],
'tunjangan_tetap_awal' => $row['tunjangan_tetap_di_awal_periode'],
'total_upah_awal' => $row['total_upah_di_awal_periode'],
'status_akhir' => $row['status_di_akhir_periode'],
'tgl_keluar' => $formatedDate4,
'status2_akhir' => $row['keterangan_keluar'],
'gaji_pokok_akhir' => $row['gaji_pokok_di_akhir_periode'],
'tunjangan_tetap_akhir' => $row['tunjangan_tetap_di_akhir_periode'],
'total_upah_akhir' => $row['total_upah_di_akhir_periode'],
'jumlah_pesangon_paid_awal' => $row['pesangon_dibayarkan_pada_periode'],
'correction_flag' => 'CORRECTED'
]);
}
}
public function headingRow(): int
{
return 4;
}
public function startRow(): int
{
return 5;
}
i already tried to put correction_flag like the example above but its just make all record uploaded marked CORRECTED eventhou there is no changes happend.
You need to first() the query, because laravel model event listeners won't work if there's mass update/create. So what you need to do is:
$tempdat = Tempdat::where('cc', Auth::user()->ccode)->where('id_tempdat', $row['id_tempdat'])->first();
if($tempdat){
$tempdat->update([
...
]);
}
And add this function to your Temptdat model:
protected static function booted()
{
parent::boot();
self::saving(function ($model) {
if ($model->isDirty()) {
$model->correction_flag = 'CORRECTED';
}
});
}

Why value is not getting inserted in table in codeigniter

In controller
Login information is added inside an array and passed to model. Why it is not inserted in table.
$loginInfo = [
'agent' => $this->getUserAgentInfo(),
'ip' => $this->request->getIPAddress(),
'logintime' => date('Y-m-d h:i:s'),
];
$data=$model->saveLoginInfo($loginInfo);
...
...
public function getUserAgentInfo()
{
$agent = $this->request->getUserAgent();
if ($agent->isBrowser())
{
$currentAgent = $agent->getBrowser();
}
elseif ($agent->isRobot())
{
$currentAgent = $this->agent->robot();
}
elseif ($agent->isMobile())
{
$currentAgent = $agent->getMobile();
}
else{
$currentAgent = 'Undefined User Agent';
}
return $currentAgent;
}
In Model
public function saveLoginInfo($data){
$this->db->table('login_activity')->set($data)->insert();
}

do not show the success message if the data hasnt been updated n a form laravel

i have a form whereby on updating the data and storing it to the database it shows a success message.if one of the inputs isn't filled it shows an error.am getting a bug whereby when i want to re-update the data and i open the form with the existing inputs when i click save the data should just redirect back to the previous page and not show the success message as the data hasnt being updated.how can i achieve this,am looking for a logic here fellow devs..here is my update function code
public function update(Request $request)
{
try {
$validation = Validator::make($request->all(), [
'systemid' => 'required',
'category' => 'required',
'subcategory' => 'required',
'prdcategory' => 'required',
'prdbrand' => 'required'
]);
Log::debug('Request: '.json_encode($request->file()));
if ($validation->fails()) {
throw new \Exception("validation_error", 19);
}
$systemid = $request->systemid;
$product_details = product::where('systemid', $systemid)->first();
$changed = false;
if ($request->has('product_name')) {
if ($product_details->name != $request->product_name) {
$product_details->name = $request->product_name;
$changed = true;
}
}
if ($request->has('category')) {
if ($product_details->prdcategory_id != $request->category) {
$product_details->prdcategory_id = $request->category;
$changed = true;
}
}
if ($request->has('subcategory')) {
if ($product_details->prdsubcategory_id != $request->subcategory) {
$product_details->prdsubcategory_id = $request->subcategory;
$changed = true;
}
if ($product_details->ptype == 'voucher') {
$voucher = voucher::where('product_id', $product_details->id)->first();
if($voucher->subcategory_id != $request->subcategory){
$voucher->subcategory_id = $request->subcategory;
$voucher->save();
$changed = true;
}
}
}
if ($request->has('prdcategory')) {
if ($product_details->prdprdcategory_id != $request->prdcategory) {
$product_details->prdprdcategory_id = $request->prdcategory;
$changed = true;
}
}
if ($request->has('prdbrand')) {
if ($product_details->brand_id != $request->prdbrand) {
$product_details->brand_id = $request->prdbrand;
$changed = true;
}
}
if ($request->has('description')) {
if ($product_details->description != $request->description) {
$product_details->description = $request->description;
$changed = true;
}
}
if ($changed == true || true) {
$product_details->save();
$msg = "Product information updated successfully";
$data = view('layouts.dialog', compact('msg'));
//i have added this code but it doesnt work
} else if($changed == false) {
return back();
$data = '';
}
}
return $data;
}
my laravel project version is 5.8
The following line will always evaluate to True
$changed == true || true
And you have a catch statement missing at the end so I had to add it.
And I advise you to simply get the dirty version of $product_details.
You can use $product_details->isDirty() // boolean.
Or even better way is to use $product_details->wasChanged() // boolean
Here is the code after some tweaks:
public function update(Request $request)
{
try {
$validation = Validator::make($request->all(), [
'systemid' => 'required',
'category' => 'required',
'subcategory' => 'required',
'prdcategory' => 'required',
'prdbrand' => 'required'
]);
Log::debug('Request: '.json_encode($request->file()));
if ($validation->fails()) {
throw new \Exception('validation_error', 19);
}
$systemid = $request->systemid;
$product_details = Product::where('systemid', $systemid)->first();
$changed = false;
// Looping for all inputs:
$fieldsToCheck = [
'name' => 'product_name',
'prdcategory_id' => 'category',
'prdsubcategory_id' => 'subcategory',
'prdprdcategory_id' => 'prdcategory',
'brand_id' => 'prdbrand',
'description' => 'description',
];
foreach ($fieldsToCheck as $productColumnName => $requestFieldName) {
$requestInput = $request->{$requestFieldName};
if ($request->has($requestFieldName)) {
if ($product_details->$productColumnName != $requestInput) {
$product_details->$productColumnName = $requestInput;
$changed = true;
}
}
// Exception for Sub Category to check for the voucher.
if ($requestFieldName == 'subcategory') {
$this->handleVoucher($requestInput);
}
}
// here I advise you to simply get the dirty version of $product_details
// you can use $product_details->isDirty() // boolean
// or even better use $product_details->wasChanged() // boolean
if ($changed) {
$product_details->save();
$msg = 'Product information updated successfully';
$data = view('layouts.dialog', compact('msg'));
} else {
return back();
// Todo Mo: No need for this line so I commented it out.
//$data = '';
}
} catch (\Exception $e) {
dd($e->getMessage(), 'Oops, error occurred');
}
return $data;
}
private function handleVoucher($product_details, $subcategory)
{
if ($product_details->ptype == 'voucher') {
$voucher = voucher::where('product_id', $product_details->id)->first();
if ($voucher->subcategory_id != $subcategory) {
$voucher->subcategory_id = $subcategory;
$voucher->save();
}
}
}

How to use save() method inside a loop in laravel

My current situation is: I must use save() method to save multiple records using loop. I know insert() will fix my problem but to maintain my code clean I have to use the same code and save() method to insert the record. I create new instance inside the loop but always only last record is being inserted. My code looks like:
public static function save($data)
{
$settings = Settings::instance();
$data['sender_address'] = urldecode($data['sender_address']);
$data['sender_address'] = json_decode($data['sender_address'], true);
extract($data);
$customerFields = ['name', 'mobile', 'alt_mobile', 'district_id', 'area_id', 'address'];
$customerObj = $customer = Customer::where('mobile', $mobile);
if ($customerObj->count()) {
$customer = $customer->first();
} else {
$customer = new Customer;
}
foreach ($customerFields as $customerField) {
if (!empty($$customerField)) {
$customer->$customerField = $$customerField;
}
}
($customerObj->count()) ? $customer->update() : $customer->save();
$order = (isset($order_id) && !empty($order_id) )? Order::find($order_id) : new Order;
$order->sender_address = $sender_address;
$order->branch_id = self::getBranchIdByAreaId($sender_address['area']);
$order->responsible_by = self::getBranchManagerIdByBranchId($order->branch_id);
$order->client_id = $client_id;
$order->customer_id = $customer->id;
$order->delivery_time = $delivery_time;
$deliveryChargeParams = [
'district_id' => $district_id,
'delivery_time' => $delivery_time,
'product_weight' => $product_weight,
'merchant_id' => $client_id,
];
$order->delivery_charge = Utility::getDeliveryCharge($deliveryChargeParams);
$order->vat = Utility::getVat($order->delivery_charge);
if (empty($order_id)) {
$order->status_id = ($role_id == Employee::CLIENT) ?
$settings['tracking']['default_status'] : Order::PACKAGINGDONE;
if (($role_id != Employee::CLIENT)) {
$order->requested = Order::PACKAGINGDONE;
}
}
$order->cash_amount = $cash_amount;
$order->cod_charge = Utility::getCodCharge($cash_amount);
$order->product_weight = $product_weight;
$order->client_reference = $client_reference;
if (empty($order_id)) {
$order->save();
$loggedInUserId = isset($data['fromApp'])?
$data['client_id'] : Auth::getUser()->id;
$order->number = self::orderNumber($order,$loggedInUserId);
$order->update();
} else {
$order->update();
}
if (($role_id != Employee::CLIENT)) {
self::updateDeliveryWithin($order);
}
PaymentAction::update($order);
}
The following method calls this save() method:
function onSave(){
$data = post();
$client_id = (Auth::getUser()->role_id == Employee::CLIENT) ? Auth::getUser()->id : $data['client_id'];
$sender_address = $data['sender_address'];
$file = Input::file('bulk_order');
$filename = time().'-'.rand(2000,99999999).'-'.$file->getClientOriginalName();
$result = $file->move('tempFiles',$filename);
$uploadedFilePath = 'tempFiles/'.$filename;
$contents = $this->csvToArray($uploadedFilePath);
// dd($contents); //exit;
unlink($uploadedFilePath);
$keys = array();
if(count($contents)){
$keys = array_keys($contents[0]);
}else{
throw new ApplicationException('Your Csv file is not in proper Format OR Empty!');
}
$fields = array('client_reference','customer_mobile','customer_alternative_mobile','customer_name','customer_district','customer_area','customer_address','product_weight_in_kg','delivery_time_in_hour','cash_collection');
$diff = array_diff($keys,$fields);
//dd($diff); exit;
if(count($diff)!=0){
throw new ApplicationException('Your Csv file is not in proper Format');
}
// dd($contents); exit;
foreach($contents as $row){
$data['name'] = $row['customer_name'];
$data['mobile'] = $row['customer_mobile'];
if(strlen($data['mobile']) == 10 ){
$data['mobile'] = '0'.$data['mobile'];
}
$data['alt_mobile'] = $row['customer_alternative_mobile'];
if(strlen($data['alt_mobile']) == 10 ){
$data['alt_mobile'] = '0'.$data['alt_mobile'];
}
$data['district_id'] = Utility::getDistrictIdByName($row['customer_district']);
$data['area_id'] = Utility::getAreaIdByName($row['customer_area']);
$data['address'] = $row['customer_address'];
$data['delivery_time'] = $row['delivery_time_in_hour'];
$data['product_weight'] = $row['product_weight_in_kg'];
$data['client_id'] = $client_id;
$data['sender_address'] = $sender_address;
$data['cash_amount'] = $row['cash_collection'];
$data['client_reference'] = $row['client_reference'];
$data['role_id'] = Auth::getUser()->role_id;
OrderAction::save($data);
}
\Flash::success('Bulk Order uploaded Successfully');
return Redirect::to('dashboard/shipments');
}
Is it possible to save multiple records with my approach? Thanks in advance.

Laravel API DB transaction with too long code. How do I modularize or optimize this code? (I am new to Laravel)

I have very complex functions in laravel APIs ( called from Mobile App).
The sample function is given below.
If someone can help to improve the code structure.
I wish to know the best practices in handling multiple transactions in a single API. Because if I move each table's entry to separate function - how do I handle errors of each one? Ex: when the quantity is not set in $request model
SUMMARY:
Can someone please break it into smaller functions?
.... Because I don't know how/where to break it into smaller ones.
public function placeOrder(Request $request)
{
$this->validate($request, [
'addressId' => 'required'
]);
$userId = Auth::user()->id;
$itemList = array();
$deliveryCharge = Store::first()->delivery_charge;
// $deliveryCharge = Store::findOrFail($request->header('StoreId'))->delivery_charge;
$total = $deliveryCharge;
$cod = $request->cod;
$useBalanceFirst = $request->useBalanceFirst;
$addressId = $request->addressId;
$list = $request->list;
$cost = 0;
// fetch all items using id in request
foreach ($list as $orderItemFromRequest) {
if (!isset($orderItemFromRequest['id']))
return $this->error("Invalid item selected");
$itemFromDB = Item::find($orderItemFromRequest['id']);
if (!isset($orderItemFromRequest['quantity']))
return $this->error("Please enter quantity for {$itemFromDB->name}");
$qty = $orderItemFromRequest['quantity'];
if ($qty > 0.0) {
if ($itemFromDB == null || $itemFromDB->available == false)
return $this->error("Invalid item selected");
$itemFromDB->quantity = $qty;
$total += ($itemFromDB->sell_rate * $itemFromDB->quantity) / $itemFromDB->rate_unit_multiple;
$cost += ($qty * $itemFromDB->purchase_rate) / $itemFromDB->rate_unit_multiple;
array_push($itemList, $itemFromDB);
}
}
if (count($itemList) == 0) {
return $this->error("At least 1 item is needed to place the order");
}
// check user balance
$user = User::findOrFail($userId);
// if balance < total -> throw error
if ($cod != true && $user->balance < $total) return $this->error("Insufficient Balance. Please recharge your wallet or use C.O.D.", 403);
$order = new Order();
$order->user_id = $user->id;
$order->total = $total;
$order->delivery_charge = $deliveryCharge;
$order->purchase_rate = $cost;
// because in-case user changes his/her name in future - the order should have the historical name & number
$order->customer_name = $user->name;
$order->customer_contact = $user->contact_no;
$order->address_id = $addressId;
if ($cod == true) {
if ($useBalanceFirst == true) {
if ($user->balance < $order->total)
$order->amount_due = $order->total - $user->balance;
else
$order->amount_due = 0;
} else {
$order->amount_due = $order->total;
}
} else
$order->amount_due = 0;
$ordertransaction = new OrderTimeLine();
$ordertransaction->created_by = Auth::user()->id;
DB::transaction(function () use ($order, $itemList, $user, $ordertransaction) {
// insert 1 entry into orders
$order->save();
$order->refresh();
$newOrderItemList = array();
// insert N entries for Items
foreach ($itemList as $requestItem) {
$item = new OrderItem();
$item->order_id = $order->id;
$item->item_id = $requestItem->id;
$item->item_name = $requestItem->name;
$item->sell_rate = $requestItem->sell_rate;
$item->purchase_rate = $requestItem->purchase_rate;
$item->quantity = $requestItem->quantity;
$item->quantity_unit = $requestItem->unit;
$item->rate_unit_multiple = $requestItem->rate_unit_multiple;
if ($requestItem->remaining_stocks <= 0) {
$item->purchase_rate_qty = 0;
} else if ($requestItem->remaining_stocks < $requestItem->quantity) {
$item->purchase_rate_qty = $requestItem->remaining_stocks;
} else
$item->purchase_rate_qty = $requestItem->quantity;
$item->save();
$item->refresh();
$requestItem->remaining_stocks = $requestItem->remaining_stocks - $requestItem->quantity;
// update remaining QTY and cost price
unset($requestItem->quantity);
if ($requestItem->remaining_stocks <= $requestItem->alert_stocks) {
// send notification
NotificationController::notifyAdminAboutStocks($requestItem);
}
$requestItem->save();
array_push($newOrderItemList, $item);
}
$order->items = $newOrderItemList;
// deduct balance from user table
$user->balance = $user->balance - $order->total + $order->amount_due;
$user->save();
$balanceAffected = 0 - $order->total + $order->amount_due;
// enter transaction in wallet_transaction table
if ($balanceAffected != 0) {
$transaction = new WalletTransaction();
$transaction->user_id = $user->id;
$transaction->amount = $balanceAffected;
$transaction->type = WALLET_ORDER_PLACED;
$transaction->order_id = $order->id;
$transaction->save();
}
$ordertransaction->status = $order->status;
$ordertransaction->order_id = $order->id;
$ordertransaction->save();
});
NotificationController::notifyAdminAboutOrder($user, $order);
return $this->success(["balance" => $user->balance, "order" => $order]);
}
You are handling too many work in the controller function.
First of all I suggest to make full use of Laravel Validation functionality. then use Laravel Collection to make your code more readable and compact. I have refactored your function as how I usually handle.
public function placeOrder(Request $request)
{
$data = $request->validate([
'addressId' => 'required',
'cod' => 'required|boolean',
'useBalanceFirst' => 'required|boolean',
'list' => 'required|array',
'list.*.quantity' => 'required|numeric',
'list.*.id' => ['required', 'numeric', Rule::exists('items')->where(function ($query) {
$query->where('available', true);
})],
]);
$user = Auth::user();
$orderItems = collect($data['list'])->map(function($listItem){
$item = Item::find($listItem['id']);
$orderItem = new OrderItem([
'item_id' => $item->id,
'item_name' => $item->name,
'sell_rate' => $item->sell_rate,
'purchase_rate' => $item->purchase_rate,
'quantity' => $listItem['quantity'],
'quantity_unit' => $item->quantity_unit,
'rate_unit_multiple' => $item->rate_unit_multiple,
]);
if ($item->remaining_stocks <= 0) {
$orderItem->purchase_rate_qty = 0;
} else if ($item->remaining_stocks < $orderItem->quantity) {
$orderItem->purchase_rate_qty = $item->remaining_stocks;
} else
$orderItem->purchase_rate_qty = $orderItem->quantity;
return $orderItem;
});
$total = $orderItems->sum(function($item){
return ($item->sell_rate * $item->quantity) / $item->rate_unit_multiple;
});
$cost = $orderItems->sum(function($item){
return ($item->quantity * $item->purchase_rate) / $item->rate_unit_multiple;
});
$deliveryCharge = Store::first()->delivery_charge;
$total += $deliveryCharge;
// if balance < total -> throw error
if (!$data['cod'] && $user->balance < $total)
{
return $this->error("Insufficient Balance. Please recharge your wallet or use C.O.D.", 403);
}
$order = new Order([
'user_id' => $user->id,
'total' => $total,
'delivery_charge' => $deliveryCharge,
'purchase_rate' => $cost,
// because in-case user changes his/her name in future - the order should have the historical name & number
'customer_name' => $user->name,
'customer_contact' => $user->contact_no,
'address_id' => $data['addressId'],
]);
if ($data['cod']) {
if ($data['useBalanceFirst']) {
if ($user->balance < $order->total)
$order->amount_due = $order->total - $user->balance;
else
$order->amount_due = 0;
} else {
$order->amount_due = $order->total;
}
} else
{
$order->amount_due = 0;
}
DB::transaction(function () use ($order, $orderItems, $user) {
// insert 1 entry into orders
$order->save();
$order->items->saveMany($orderItems);
// deduct balance from user table
$user->balance = $user->balance - $order->total + $order->amount_due;
$user->save();
$ordertransaction = OrderTimeLine::create([
'created_by' => $user->id,
'status' => $order->status,
'order_id' => $order->id,
]);
});
return $this->success(["balance" => $user->balance, "order" => $order]);
}
As you have noticed I have removed notification and user wallet transaction code as these should be updated asynchronously with no impact on your user experience. I suggest you take a look at Laravel Events.

Resources