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;
}
}
Related
How to create a validation when importing CSV. I'm using the "maatwebsite/excel": "^3.1" if the imported csv column header name is not exact with the database column it should display some validation. This is my reference LaravelDaily
/
Laravel-8-Import-CSV
Importing CSV
public function parseImport(CsvImportRequest $request)
{
if ($request->has('header')) {
$headings = (new HeadingRowImport)->toArray($request->file('csv_file'));
$data = Excel::toArray(new AwardeesImport, $request->file('csv_file'))[0];
} else {
$data = array_map('str_getcsv', file($request->file('csv_file')->getRealPath()));
}
if (count($data) > 0) {
$csv_data = array_slice($data, 0, 6);
$csv_data_file = CsvData::create([
'csv_filename' => $request->file('csv_file')->getClientOriginalName(),
'csv_header' => $request->has('header'),
'csv_data' => json_encode($data)
]);
} else {
return redirect()->back();
}
return view('admin.import-csv.import-fields', [
'headings' => $headings ?? null,
'csv_data' => $csv_data,
'csv_data_file' => $csv_data_file
])->with('success', 'The CSV file imported successfully');;
}
When parsing CSV
public function processImport(Request $request)
{
$data = CsvData::find($request->csv_data_file_id);
$csv_data = json_decode($data->csv_data, true);
foreach ($csv_data as $row) {
$awardees = new SIS();
foreach (config('app.db_fields') as $index => $field) {
if ($data->csv_header) {
$awardees->$field = $row[$request->fields[$field]];
} else {
$awardees->$field = $row[$request->fields[$index]];
}
}
$awardees->save();
}
return redirect()->action([ImportController::class, 'index'])->with('success', 'Import finished.');
}
CsvImportRequest
public function rules()
{
return [
'csv_file' => 'required|mimes:csv,txt'
];
}
config/app.php
'db_fields' => [
'email_address',
'surname',
'first_name',
'middle_name',
'course',
'year_level',
'contact_number',
'gwa_1st',
'gwa_2nd',
'applying_for',
'remarks',
'comments'
]
if one of those field is missing it should show the validation error
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']);
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
];
}
I am using Laravel-5.8 and Guzzle to consume an external api:
public function index()
{
try{
$myparam = 'JKK123';
$client = new Client();
$res = $client->request('GET','https://examplet/tracking/$myparam', [
'query' => ['key' => 'jkkffd091']
])->getBody();
$geoLocation = json_decode($res->getContents(), true);
$currentLocation = collect($geoLocation)->sortByDesc(function ($data) {
return Carbon::parse($data['Timestamp'])->format('d-m-Y h:i:s');
})->first();
$currentLocationFilter = explode(',', $currentLocation['current_asset_position_coord'] ?? '');
dd($currentLocationFilter);
return view('index', [
'currentLocation' => $currentLocation,
'currentLocationFilter' => $currentLocationFilter,
'geoLocation' => $geoLocation
]);
}catch (Exception $exception) {
Log::error($exception);
return back();
}
}
I am trying to pass the variable as parameter to the API. I didn't put it directly because it changes. I just tried to test.
When I did this as shown in the code above
$res = $client->request('GET','https://examplet/tracking/$myparam', [ ...
and then
dd($currentLocationFilter);
I got:
array:1 [▼
0 => ""
]
But when I put the value directly,
$res = $client->request('GET','https://examplet/tracking/JKK123', [
I got the required result:
array:2 [▼
0 => "2.1234565432145"
1 => "1.7864321249555"
]
How do I paa the variable as parameter into the external API?
Thanks
Use double quotes for executing variable like this:
$res = $client->request('GET',"https://examplet/tracking/{$myparam}", [...
Hi all you smart individuals i'm hitting a solid wall here with someone else code that i'm trying to fix a issue.
The issue is that when this query builder has got all the results there seems to be some coming back with null values and i'm not sure how to remove them before I paginate the data, I know how to do it if it was a collection however maybe some of you might be-able to help me.
so currently the logic goes into this pagination
$return = $tld->paginate($request->get('limit'))->toArray();
$tld being the eloquent builder.
Which then gets sent into this function that was created..
$return = $this->makePagination($return);
public function makePagination($object = [], $filters = []) {
return [
'data' => [
'items' => $object['data'],
'pagination' => [
'from' => $object['from'],
'to' => $object['to'],
'total' => $object['total'],
'per_page' => $object['per_page'],
'first_page' => [
'number' => 1,
'url' => $object['first_page_url']
],
'last_page' => [
'number' => $object['last_page'],
'url' => $object['last_page_url']
],
'next_page' => [
'number' => $object['current_page'] + 1,
'url' => $object['next_page_url']
],
'prev_page' => [
'number' => $object['current_page'] - 1,
'url' => $object['prev_page_url']
]
],
'params' => $filters
]
];
}
But then i'm getting a response like this with Null values and I would like to remove them before any of this pagination happens
{
"data": {
"items": [
{
"id": 13771,
},
null,
{
"id": 4125,
},
Side note if I run $tld->get() I can see all the results and there are null values in there so if anyone can show me how to remove the null values that would be a great help <3 you all if you can help me ...
Update
Ive also tried $tld->get()->filter(); and thats also not removing the null values I still get this response
[
{
"id": 13771,
},
null,
{
"id": 789,
}
]
I think I fixed it with a little hack
$filtered = collect(array_values(array_filter($tld->get()->toArray())));
return $this->paginate($filtered, $request->get('limit') ?? 15 , $page = null, $options = []);
and then created a collection paginator
public function paginate($items, $perPage = 15, $page = null, $options = [])
{
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}
#Bob Hiller Please use whereNotNull in query to remove null entries.
$tld=$query->get();
$tld->filter(function ($value) { return !is_null($value); });
$return = $tld->paginate($request->get('limit'))->toArray();