select column from an array based on id - laravel

I want to filter through this array $bank_totals and select a value of amount only.
$bank_totals = $bank_totals->bank_balances();
"id" => 1
"bank" => "KCB"
"amount" => 7622.0
]
1 => array:3 [
"id" => 2
"bank" => "I & M Bank"
"amount" => 25000.0
am getting the id from user input $data['id']; I want when the $data['id'] = 2 example the value shown is 25000
$data = request()->all();
$bank_totals = $bank_totals->bank_balances();
(to appear here)
here is my bank_balances method
class TransactionsRepository
{
public function bank_balances(){
$banks_data = Bank::all();
$banks_totals = [];
foreach ($banks_data as $bank){
$totals = (BankingTransactions::where('bank_id', $bank->id)->sum('amount')) -
((PettyCash::where('bank_id', $bank->id)->sum('amount')) + ((PayDoctor::where('bank_id', $bank->id)
->sum('total_paid'))));
array_push($banks_totals,
[
'id'=>$bank->id,
'bank'=>$bank->name,
'amount'=>$totals,
]);
}
return $banks_totals;
}
}

Replace your bank_balances method with this:
public function bank_balances($id = null) {
$banks_data = Bank::all();
$banks_totals = [];
if (is_null($id)) {
foreach ($banks_data as $bank) {
$totals = (BankingTransactions::where('bank_id', $bank->id)->sum('amount')) -
((PettyCash::where('bank_id', $bank->id)->sum('amount')) + ((PayDoctor::where('bank_id', $bank->id)
->sum('total_paid'))));
array_push(
$banks_totals,
[
'id' => $bank->id,
'bank' => $bank->name,
'amount' => $totals,
]
);
}
return $banks_totals;
} else {
return (BankingTransactions::where('bank_id', $id)->sum('amount')) -
((PettyCash::where('bank_id', $id)->sum('amount')) + ((PayDoctor::where('bank_id', $id)
->sum('total_paid'))));
}
}
And use it like this:
$bank_totals = $bank_totals->bank_balances($data['id']);

Related

Laravel - How to update table multiple rows at once

I have this variable called $projectFieldOptions and it's output is like this:
https://prnt.sc/7HtxrfTy9HiI.
Now, In the Controller I need to update this. What I am doing this, first delete all the existing rows based on id_feed and id_project and then loop through this variable $projectFieldOptions and insert it. Like this:
if( $request->feed_type !== 'scrape' ) {
$delete_mapping = DB::connection($db_name)->table($db_name . '.feed_mappings')
->where('id_feed', '=', $id_feed)
->where('id_project', '=', $token)
->delete();
}
// now insert
$field_mapping = true;
if( $request->feed_type !== 'scrape' ) {
if( count($projectFieldOptions) ) {
foreach ($projectFieldOptions as $mapping) {
$data[] = [
'id_feed' => $id_feed,
'id_project' => $token,
'import_field_slug' => $mapping['value'],
'internal_field_slug' => $mapping['custom'] ? $mapping['custom_field'] : $mapping['text'],
'custom_field' => $mapping['custom'],
'updates' => $mapping['updates'],
'removes' => $mapping['removes'],
'import' => 1,
'date_add' => now(),
'date_upd' => now()
];
}
} else {
$data = [];
}
$field_mapping = DB::connection($db_name)->table($db_name . ".feed_mappings")->insert($data);
}
Now, I don't want to delete existing rows instead I want to update those rows based on the id_feed_mappings. Can you tell how can I do this?
Check if this would work, to update based on id_feed_mappings value, you can use the ->where('id_feed_mappings', '=' ,'a value or variable') before ->update($data)
if( $request->feed_type !== 'scrape' ) {
// try using update instead of insert
$field_mapping = true;
if( $request->feed_type !== 'scrape' ) {
if( count($projectFieldOptions) ) {
foreach ($projectFieldOptions as $mapping) {
$data[] = [
'id_feed' => $id_feed,
'id_project' => $token,
'import_field_slug' => $mapping['value'],
'internal_field_slug' => $mapping['custom'] ? $mapping['custom_field'] : $mapping['text'],
'custom_field' => $mapping['custom'],
'updates' => $mapping['updates'],
'removes' => $mapping['removes'],
'import' => 1,
'date_add' => now(),
'date_upd' => now()
];
}
} else {
$data = [];
}
$field_mapping = DB::connection($db_name)->table($db_name . ".feed_mappings")->update($data);
}

Failed asserting that a row in the table student.sections matches the attributes

Hello im new to PHPUnit with minimum knowledge in laravel.
Im trying to test this method that mass create student section
public function setStudentsSection(Request $request)
{
$enrollments = Enrollment::whereIn('student_id', $request->students)->where('session_id', $request->session_id)->get();
$program_section = ProgramSection::withCount('students')->find($request->program_section_id);
if(($program_section->students_count + count($enrollments)) <= $program_section->max_students) {
foreach($enrollments as $enrollment) {
$response = StudentSection::create([
'student_id' => $enrollment->student_id,
'enrollment_id' => $enrollment->id,
'section_id' => $request->program_section_id,
'created_at' => Carbon::now()
]);
return $response;
}
}
return response()->json(['errors' => ['message' => 'Selected Section is full.']], 405);
}
UPDATE
Here's the test case. Im trying to match the method that i've modified with my test, but im failing to do so.
public function testCanMassAssignSection()
{
$sectioning_data = $this->setMassSectioning(10);
$this->json('POST', 'api/enrollments/set-students-section', $sectioning_data['data'])
->assertStatus(201);
$student_section_data = ['student_id' => $sectioning_data['student_ids'], 'section_id' => $sectioning_data['program_section']->id];
$this->assertDatabaseHas('student.sections', $student_section_data);
}
private function setMassSectioning($max_students)
{
$session = Session::factory()->create();
$program_section = ProgramSection::factory()->create(['session_id' => $session->id, 'max_students' => $max_students]);
$enrollments = Enrollment::factory(['session_id' => $session->id])->count(3)->create();
$student_ids = array();
foreach($enrollments as $enrollment) {
array_push($student_ids, $enrollment->student_id);
}
return [
'data' => ['program_section_id' => $program_section->id, 'session_id' => $session->id, 'students' => $student_ids],
'student_ids' => $enrollment->student_id,
'program_section' => $program_section
];
}
UPDATE
Here's the error the i get.
1) Test\Feature\EnrollmentTest::testCanMassAssignSection
Failed asserting that a row in the table [student.sections] matches the attributes {
"student_id": 2765,
"section_id": 1649
}.
Found: [
{
"id": 262,
"student_id": 2763,
"section_id": 1649,
"created_at": "2022-08-24 09:32:05",
"updated_at": "2022-08-24 09:32:05",
"enrollment_id": 1740
}
].
Still can't make it to match. I do not know what im doing wrong.
Solve! I just create $student data and added to $enrollments now assert in database match. Although don't know what exactly is happening on the background.
I think when i added to enrollments variable the 'student_id' => $student->id it creates those 3 records.
private function setMassSectioning($max_students)
{
$session = Session::factory()->create();
$student = Student::factory()->create();
$program_section = ProgramSection::factory()->create(['session_id' => $session->id, 'max_students' => $max_students]);
$enrollments = Enrollment::factory(['session_id' => $session->id, 'student_id' => $student->id])->count(3)->create();
$student_ids = array();
foreach($enrollments as $enrollment) {
array_push($student_ids, $enrollment->student_id);
}
return [
'data' => ['program_section_id' => $program_section->id, 'session_id' => $session->id, 'students' => $student_ids],
'student_ids' => $enrollment->student_id,
'program_section' => $program_section
];
}

Undefined array key "project" - work with api, cteating console command

I have code where I use function for get data from api getTimeEntriesInfo
public function getTimeEntriesInfo(int $user_id): array
{
$users = self::getAllData('time_entry', ['user_id'=>$user_id]);
return $users['time_entries'];
}
Then I create console command artisan to save all data from api:
<?php
class LinkNew extends Command
{
public function handle()
{
$redmineService = new RedmineAPIService();
$users = $redmineService->getUsersInfo();
foreach ($users as $user) {
$data = $redmineService->getTimeEntriesInfo($user['id']);
//dd($data);
$project = $redmineService->getTimeEntriesInfo($user['project']);
$activity = $redmineService->getTimeEntriesInfo($user['activity']);
$issue = $redmineService->getTimeEntriesInfo($user['issue']);
$comments = $redmineService->getTimeEntriesInfo($user['comments']);
if ($this->confirm('Is this information correct?')) {
$link = new TimeEntry();
$link->project = $project;
$link->activity = $activity;
$link->issue = $issue;
$link->comments = $comments;
//dd($link->getAttributes());
$link->save();
$this->info("Saved.");
}
}
return 0;
}
}
But I have mistake Undefined array key "project". Why?
dd($data)
248 => array:10 [
"id" => 5379
"project" => array:2 [ …2]
"issue" => array:1 [ …1]
"user" => array:2 [ …2]
"activity" => array:2 [ …2]
"hours" => 1.5
"comments" => "Some comment"
"spent_on" => "2022-05-27"
"created_on" => "2022-05-27T09:31:18Z"
"updated_on" => "2022-05-27T09:31:18Z"
]
249 => array:10 [
"id" => 5369
"project" => array:2 [ …2]
"issue" => array:1 [ …1]
"user" => array:2 [ …2]
"activity" => array:2 [ …2]
"hours" => 1.0
"comments" => "Some comment"
"spent_on" => "2022-05-27"
"created_on" => "2022-05-27T05:00:19Z"
"updated_on" => "2022-05-27T05:00:19Z"
]
upd
public function handle()
{
$redmineService = new RedmineAPIService();
$users = $redmineService->getUsersInfo();
foreach ($users as $user) {
$data = $redmineService->getTimeEntriesInfo($user['id']);
//isset($user);
foreach ($users as $user) {
//$data = $redmineService->getTimeEntriesInfo($user['id']);
//dd($data);
$project = $data['project'];
$activity = $redmineService->getTimeEntriesInfo($data['activity']);
$issue = $redmineService->getTimeEntriesInfo($data['issue']);
$comments = $redmineService->getTimeEntriesInfo($user['comments']);
if ($this->confirm('Is this information correct?')) {
$link = new TimeEntry();
$link->project = $project;
$link->activity = $activity;
$link->issue = $issue;
$link->comments = $comments;
//dd($link->getAttributes());
$link->save();
$this->info("Saved.");
}
}
}
return 0;
}
I resolved it like:
public function handle()
{
$redmineService = new RedmineAPIService();
$timeEntries = $redmineService->getTimeEntriesInfo();
foreach ($timeEntries as $timeEntry) {
$link = new TimeEntry();
$link->redmine_id = $timeEntry['id'];
$link->project = $timeEntry['project']['name'];
$link->issue = $timeEntry['issue']['id'];
$link->user = $timeEntry['user']['name'];
$link->activity = $timeEntry['activity']['name'];
$link->hours = $timeEntry['hours'];
$link->comments = $timeEntry['comments'];
$link->save();
}
return 0;
}
}

Laravel 1 row missing while inserting and

$purchase_line_datas = PurchaseLine::where('transaction_id',
$transaction->id)->get(); $i = 0;
$input = [];
foreach ($purchase_line_datas as $key => $purchase_line_data) {
if (!$enable_stock_transfer) {
$qty_available = $this->productUtil->num_uf($purchases[$i]['quantity']);
} else {
$qty_available = 0;
}
$item = array(
"business_id" => $business_id,
"transaction_id" => $purchase_line_data->transaction_id,
"purchase_line_id" => $purchase_line_data->id,
"variation_id" => $purchase_line_data->variation_id,
"contact_id" => $transaction_data['contact_id'],
"product_id" => $purchase_line_data->product_id,
"ref_no" => $ref_no,
"new_barcode" => $purchase_line_data->barcode,
"default_sell_price" => $this->productUtil->num_uf($purchases[$i]['default_sell_price']),
"purchase_qty" => $this->productUtil->num_uf($purchases[$i]['quantity']),
"qty_available" => $this->productUtil->num_uf($qty_available),
"created_at" => Carbon::now()
);
array_push($input, $item);
$i++;
}
ProductPurchaseSl::insert($input);
in this code I am inserting an array but after inserting.. it's showing that one row is missing.And it's happening very often.I couldn't be able to solve this problem.

saving number field with a value of zero in Laravel 5.5

I have a form that accepts delivery of products which I noticed if I enter 0 in the quantity field it doesn't save in the database even if I add data in the calendar or in Notes field.
I already commented out the \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,iin kernel.php still doesn't work.
how can I forced laravel to save my data even if I want to put 0 in quantity? thanks in advance!
update
public function store(Request $request)
{
$input = $request->all();
$items = [];
for ($i = 0; $i <= count($input['order_id']); $i++) {
if (empty($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;
$acceptItem = [
'order_id' => $input['order_id'][$i],
'product_id' => $input['product_id'][$i],
'order_item_id' => $input['order_item_id'][$i],
'delivery_date' => $input['delivery_date'][$i],
'company_id' => $input['company_id'][$i],
// 'stock_in_qty' => intval($input['stock_in_qty'])[$i],
'stock_in_qty' => $input['stock_in_qty'][$i],
// 'stock_out_qty' => $input['stock_out_qty'][$i],
// 'transfer_to' => $input['transfer_to'][$i],
'delivery_note' => $input['delivery_note'][$i],
'user_id' => $input['user_id'][$i],
];
array_push($items, Warehouse1stocks::create($acceptItem));
$stockSummary = Warehouse1StockSummaries::firstOrCreate(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['stock_in_qty'][$i],
'qty_out' => null,
]);
if (!$stockSummary->wasRecentlyCreated) {
$stockSummary->increment('qty_in', $input['stock_in_qty'][$i]);
}
}
if ($input['rd'] == $input['stock_in_qty'] || $input['rd'] == 0) {
$order_idAcceptedItem = $acceptItem['order_id'];
$setStatus = \App\Orders::where('id', '=', $order_idAcceptedItem)->first();
if ($setStatus) {
$setStatus->status_id = 4;
}
$setStatus->save();
} else {
$order_idAcceptedItem = $acceptItem['order_id'];
$setStatus = \App\Orders::where('id', '=', $order_idAcceptedItem)->first();
if ($setStatus) {
$setStatus->status_id = 3;
}
$setStatus->save();
}
return redirect()->route('orders.index');
}
empty() will return true with 0 or '0' which will mean that if you try to change the quantity to 0 the for loop will just continue on to the next loop. If you need to check if the value exists you can instead use isset().
Changing your first if statement to the following should be all you need:
if(!isset($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;

Resources