Insert multiple data from other table in codeigniter - codeigniter

I want to save the data where id_perencanaan is selected. I've tried a lot of ways, but have not found the answer.
Controller:
public function salin_barang_perencanaan($id_perencanaan) {
$barang_perencanaan = $this->perencanaan_barang_model->barang_perencanaan($id_perencanaan);
// echo "<pre>";
// print_r($barang_perencanaan);
if($barang_perencanaan->id_perencanaan == 0) {
$data = array(
'id_perencanaan_barang' => $barang_perencanaan->id_perencanaan_barang,
'id_golongan_barang' => $barang_perencanaan->id_golongan_barang,
'id_bidang_barang' => $barang_perencanaan->id_bidang_barang,
'id_kelompok_barang' => $barang_perencanaan->id_kelompok_barang,
'id_sub_kelompok_barang' => $barang_perencanaan->id_sub_kelompok_barang,
'id_jenis_barang' => $barang_perencanaan->id_jenis_barang,
'id_perencanaan' => $barang_perencanaan->id_perencanaan,
'nomor_barang' => $barang_perencanaan->nomor_barang,
'nama_barang' => $barang_perencanaan->nama_barang,
'harga_satuan' => $barang_perencanaan->harga_satuan,
'jumlah_barang' => $barang_perencanaan->jumlah_barang,
'total_harga' => $barang_perencanaan->total_harga,
'penggunaan_barang' => $barang_perencanaan->penggunaan_barang,
'keterangan' => $barang_perencanaan->keterangan,
'tanggal_post' => date('Y-m-d H:i:s'),
'id_user' => $this->session->userdata('id')
);
$this->perencanaan_model->salin_barang_perencanaan($data);
$this->session->set_flashdata('sukses', 'Perencanaan dalam tahap pengadaan');
redirect(base_url('pengadaan'));
}
$this->session->set_flashdata('sukses', 'Proses perencanaan telah dibatalkan');
redirect(base_url('perencanaan'));
}
And my model :
public function salin_barang_perencanaan($data) {
// $this->db->trans_start();
$this->db->where('id_perencanaan',$data['id_perencanaan']);
$this->db->insert_batch('pengadaan_barang',$data);
// $this->db->trans_complete();
}
I am very grateful for your help...

The problem has been resolved, the following is the code I used:
Controller :
public function salin_barang_perencanaan($id_perencanaan) {
$barang_perencanaan = $this->perencanaan_barang_model->barang_perencanaan($id_perencanaan);
// echo "<pre>";
// print_r($barang_perencanaan);
// if($barang_perencanaan->id_perencanaan == 0) {
foreach($barang_perencanaan as $barang_perencanaan){
$data = array(
'id_perencanaan_barang' => $barang_perencanaan['id_perencanaan_barang'],
'id_golongan_barang' => $barang_perencanaan['id_golongan_barang'],
'id_bidang_barang' => $barang_perencanaan['id_bidang_barang'],
'id_kelompok_barang' => $barang_perencanaan['id_kelompok_barang'],
'id_sub_kelompok_barang' => $barang_perencanaan['id_sub_kelompok_barang'],
'id_jenis_barang' => $barang_perencanaan['id_jenis_barang'],
'id_perencanaan' => $barang_perencanaan['id_perencanaan'],
// 'id_pengadaan' => $last_id,
'nomor_barang' => $barang_perencanaan['nomor_barang'],
'nama_barang' => $barang_perencanaan['nama_barang'],
'harga_satuan' => $barang_perencanaan['harga_satuan'],
'jumlah_barang' => $barang_perencanaan['jumlah_barang'],
'total_harga' => $barang_perencanaan['total_harga'],
'penggunaan_barang' => $barang_perencanaan['penggunaan_barang'],
'keterangan' => $barang_perencanaan['keterangan'],
'tanggal_post' => date('Y-m-d H:i:s'),
'id_user' => $barang_perencanaan['id_user']
);
$this->perencanaan_model->salin_barang_perencanaan($data);
}
$this->session->set_flashdata('sukses', 'Perencanaan dalam tahap pengadaan');
redirect(base_url('pengadaan'));
// }
// $this->session->set_flashdata('sukses', 'Proses perencanaan telah dibatalkan');
// redirect(base_url('perencanaan'));
}
And my model :
public function salin_barang_perencanaan($data) {
$this->db->trans_start();
$this->db->insert('pengadaan_barang' ,$data ,array('id_perencanaan' => $data['id_perencanaan']));
$this->db->trans_complete();
}

Related

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
];
}

Site refresh time is long in laravel?

Hello and do not be tired!!
My admin panel pages are hard to load...It takes 15 seconds for the pages to load!!
The problem is with my routes!!!
Because when I define the path as follows, the pages load quickly :
Route::get('users/index', function () {
return view('admin.index');
});
But the route I have defined is as follows :
Route::group(['middleware' => ['auth' , 'InfoFolder' , 'verified' , 'Roles'] , 'prefix' => 'users/'] , function(){
Route::get('{url}', [UrlController::class , 'urlpanel'])->name('users_url');
});
And the control I have defined :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UrlController extends Controller
{
//
public function urlpanel($url ){
$admin = "admin";
$pages = "admin.pages";
$charts = "admin.pages.charts";
$examples = "admin.pages.examples";
$forms = "admin.pages.forms";
$mailbox = "admin.pages.mailbox";
$tables = "admin.pages.tables";
$UI = "admin.pages.UI";
$link_panel = [
'index' => "$admin.index",
'list_users' => "$admin.list_users",
'index3' => "$admin.index3",
'calendar' => "$pages.calendar",
'widgets' => "$pages.widgets",
'chartjs' => "$charts.chartjs",
'flot' => "$charts.flot",
'inline' => "$charts.inline",
'404' => "$examples.404",
'500' => "$examples.500",
'blank' => "$examples.blank",
'invoice-print' => "$examples.invoice-print",
'invoice' => "$examples.invoice",
'lockscreen' => "$examples.lockscreen",
'login' => "$examples.login",
'profile' => "$examples.profile",
'register' => "$examples.register",
'product_add' => "$forms.product_add",
'editors' => "$forms.editors",
'general' => "$forms.general",
'compose' => "$mailbox.compose",
'mailbox' => "$mailbox.mailbox",
'read-mail' => "$mailbox.read-mail",
'data' => "$tables.data",
'simple' => "$tables.simple",
'buttons' => "$UI.buttons",
'general' => "$UI.general",
'icons' => "$UI.icons",
'sliders' => "$UI.sliders",
];
if(!in_array($link_panel[$url] , $link_panel)){
return abort(404);
}
return view($link_panel[$url]);
}
}
How can I increase the loading speed of my website?
The project has been uploaded to Localhost
:)
Try to check the middlewares you are using. Maybe in one of the middlewares there is some time consuming action.

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.

How to add months dynamically which is stored in database as a header in excel file while exporting using laravel?

Suppose I have items in database which is stored from an Excel file. All the items should be below the header of the months. I have also stored months from the file in the database. So, I want those months to be the header of those items and it's related records. In simple words, I want the header to be dynamic. This is what I have done.
I have tried many code scripts but nothing works. Like Laravel, Excel etc. Can anyone suggest me a good approach?
public function test(){
$data = Item::where('category_id',7)->get()->toArray();
$data2 = month::all();
$itemsArray[] = ['Category Id','Item Name','Created At','Updated At'];
foreach ($data as $value) {
// dd($value);
$itemsArray[] = array(
'Category Id' => $value['category_id'],
'Item Name' => $value['name'],
'Created At' => $value['created_at'],
'Updated At' => $value['updated_at'],
);
}
// Generate and return the spreadsheet
Excel::create('Items', function($excel) use ($itemsArray) {
// Set the spreadsheet title, creator, and description
$excel->setTitle('Items');
// Build the spreadsheet, passing in the items array
$excel->sheet('Items', function($sheet) use ($itemsArray) {
$cellRange = 'A1:D1';
// $spreadsheet->getActiveSheet()->getStyle('A1:D4')
// ->getAlignment()->setWrapText(true);
$sheet->getStyle($cellRange)->getFont()->setBold( true );
$sheet->getStyle($cellRange)->getFont()->setSize( '15' );
$sheet->setBorder($cellRange, 'thick' );
$sheet->getStyle($cellRange)->applyFromArray(array(
'fill' => array(
// 'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'A5D9FF')
)
));
$sheet->fromArray($itemsArray, null, 'A1', false, false);
});
$excel->setCreator('Laravel')->setCompany('Dev505');
$excel->setDescription('Items file');
})->download('xlsx');
}
I need help for getting the actual result.
Akhtar i suggest use to kindly install the Carbon package
https://carbon.nesbot.com/docs/
Try by updating the below code.
$data = Item::where('category_id',7)->get(); // removed toArray()
$data2 = month::all();
$itemsArray[] = ['Category Id','Item Name','Created At','Updated At'];
foreach ($data as $key=>$value) {
$itemsArray[] = array(
'month' => Carbon::now()->addMonth($key)->format('m-Y');
'Category Id' => $value['category_id'],
'Item Name' => $value['name'],
'Created At' => $value['created_at'],
'Updated At' => $value['updated_at'],
);
}
This is the actual code which I have used for excel file. I have solved my problem. Thanks and yeah I am posting this code, if anyone can get help from it.
public function export(){
$data = Category::all();
foreach ($data as $value) {
$value['items'] = Item::where('category_id',$value['id'])->get();
foreach ($value['items'] as $vl) {
$vl['record'] = Record::where('item_id',$vl['id'])->get();
}
}
$data2 = month::pluck('id','month');
foreach ($data2 as $key => $value) {
$m[] = $key;
}
array_unshift($m, 'Categories'); //Insert new element at the start of array
array_push($m, 'Total');
$itemsArray[] = $m;
foreach ($data as $value) {
$itemsArray[] = array(
$itemsArray[0][0] => $value['name'],
// $itemsArray[0][13] => 'Total',
);
foreach ($value['items'] as $val) {
$records_array = [];
$i = 0;
foreach ($val['record'] as $val5) {
$recordval = $val5['value'];
$records_array[$i] = $val5['value'];
$i++;
}
$itemsArray[] = array(
$itemsArray[0][0] => $val['name'],
$itemsArray[0][1] => $records_array[0],
$itemsArray[0][2] => $records_array[1],
$itemsArray[0][3] => $records_array[2],
$itemsArray[0][4] => $records_array[3],
$itemsArray[0][5] => $records_array[4],
$itemsArray[0][6] => $records_array[5],
$itemsArray[0][7] => $records_array[6],
$itemsArray[0][8] => $records_array[7],
$itemsArray[0][9] => $records_array[8],
$itemsArray[0][10] => $records_array[9],
$itemsArray[0][11] => $records_array[10],
$itemsArray[0][12] => $records_array[11],
// $itemsArray[0][13] => 'Total',
);
}
}
// Generate and return the spreadsheet
Excel::create('Items', function($excel) use ($itemsArray) {
// Set the spreadsheet title, creator, and description
$excel->setTitle('Items');
// Build the spreadsheet, passing in the items array
$excel->sheet('Items', function($sheet) use ($itemsArray) {
$cellRange = 'A1:M1';
$sheet->getStyle($cellRange)->getFont()->setBold( true );
$sheet->getStyle($cellRange)->getFont()->setSize( '12' );
$sheet->setBorder($cellRange, 'thin' );
$sheet->getStyle($cellRange)->applyFromArray(array(
'fill' => array(
// 'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'A5D9FF')
)
));
$sheet->fromArray($itemsArray, null, 'A1', false, false);
});
$excel->setCreator('Laravel')->setCompany('Dev505');
$excel->setDescription('Items file');
})->download('xlsx');
}

How to pass array in POST API?

I'm trying to post booking content with array of passengers but it always return invalid argument supplied for foreach(). What seems to be the problem ?
public function postBooking(Request $request)
{
$user = JWTAuth::parseToken()->authenticate();
$booking = Booking::create([
'service_name' => $request->get('service_name'),
'service_package' => $request->get('service_package'),
'travel_date' => $request->get('travel_date'),
'travel_day' => $request->get('travel_day'),
'travel_time' => $request->get('travel_time'),
'remark' => $request->get('remark'),
'booking_name' => $request->get('booking_name'),
'mobile_number' => $request->get('mobile_number'),
'email' => $request->get('email'),
'nationality' => $request->get('nationality'),
'user_id' => $user->user_id,
]);
$passengers = $request['passengers'];
if(is_array($passengers))
{
foreach($passengers as $passenger)
{
$passenger = Passenger::create([
'passenger_name' => $passenger['passenger_name'],
'ic_passport' => $passenger['ic_passport'],
'booking_id' => $booking->booking_id
]);
}
}
$response = (object)[];
$response->booking = $booking->makeHidden('users');
$response->passengers = $passengers;
return response()->json(['data'=>$response, 'status'=>'ok']);
}
var_dump the $passengers, in my opinion ,the way u get the data from $request is wrong, u show use var_dump()or dd() to see the structure of $request and mostly u can solve the problem.

Resources