How to get excel header and title in Maatwebsite? - laravel

Excel::load($file->getRealPath())->get();
This returns only items, not header.

You can get file title with:
$file = Excel::load($file->getRealPath())
$file->getTitle();
You can also call getTitle() on individual sheets:
foreach ($file->get() as $sheet) {
echo $sheet->getTitle();
}

use Maatwebsite\Excel\Concerns\WithProperties;
class InvoicesExport implements WithProperties
{
public function properties(): array
{
return [
'creator' => 'Patrick Brouwers',
'lastModifiedBy' => 'Patrick Brouwers',
'title' => 'Invoices Export',
'description' => 'Latest Invoices',
'subject' => 'Invoices',
'keywords' => 'invoices,export,spreadsheet',
'category' => 'Invoices',
'manager' => 'Patrick Brouwers',
'company' => 'Maatwebsite',
];
}
}
try this

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

laravel save pdf no such file or directory

So I want to save a pdf file to a directory on my local server but it keeps saying that the directory does not exist.
So first of all where would you store PDF files that are not accessible to by externals (so not in the public folder).
So this is my code. The download works perfectly.
public function generatePDF()
{
$this->mailorder = Session::get('order');
$this->cart = Session::get('cart');
$data = [
'id' => $this->mailorder->id,
'client' => $this->mailorder->Contact,
'country' => $this->mailorder->country,
'city' => $this->mailorder->city,
'street' => $this->mailorder->street,
'postal' => $this->mailorder->postal,
'phone' => $this->mailorder->phone,
'email' => $this->mailorder->email,
'dateIn' => $this->mailorder->dateIn,
'dateOut' => $this->mailorder->dateOut,
'subtotal' => $this->mailorder->subtotal,
'tax' => $this->mailorder->tax,
'total' => $this->mailorder->total,
'cart' => $this->mailorder->cart,
'delivery' => $this->mailorder->delivery,
];
$path = "order_{$this->mailorder->id}_{$this->mailorder->Contact}";
$pdf = PDF::loadView('pdf.orderConfirmationPdf', $data)->save('storage/app/public/'.$path.'.pdf');
;
return $pdf->download(''.$path.'.pdf');
}
First of all, you should check if the directory exists with File facade. If it does not exist, you must make the directory.
if(!File::exists($directory_path)) {
File::makeDirectory($directory_path);
}
If the error still occurs, you must force it to make the directory:
if(!File::exists($directory_path)) {
File::makeDirectory($directory_path, $mode = 0755, true, true);
}
After that, you can save the file in that directory.
Second, if you don't want to save the file in the public directory. you must save it in storage.By simply call storage_path($file_path). this way laravel saves the file under storage/app/public directory.
after that, you can get the URL of the file according to this answer.
I figured it out thank you for your answer.
This is my code:
public function generatePDF()
{
$this->mailorder = Session::get('order');
$this->cart = Session::get('cart');
$data = [
'id' => $this->mailorder->id,
'client' => $this->mailorder->Contact,
'country' => $this->mailorder->country,
'city' => $this->mailorder->city,
'street' => $this->mailorder->street,
'postal' => $this->mailorder->postal,
'phone' => $this->mailorder->phone,
'email' => $this->mailorder->email,
'dateIn' => $this->mailorder->dateIn,
'dateOut' => $this->mailorder->dateOut,
'subtotal' => $this->mailorder->subtotal,
'tax' => $this->mailorder->tax,
'total' => $this->mailorder->total,
'cart' => $this->mailorder->cart,
'delivery' => $this->mailorder->delivery,
];
$filename = "order_{$this->mailorder->id}_{$this->mailorder->Contact}";
$path = storage_path('pdf/orders');
if(!File::exists($path)) {
File::makeDirectory($path, $mode = 0755, true, true);
}
else {}
$pdf = PDF::loadView('pdf.orderConfirmationPdf', $data)->save(''.$path.'/'.$filename.'.pdf');
;
return $pdf->download(''.$filename.'.pdf');
}

[cakePHP3]how to debug a failed save

This is my code , I have problems with making a simple save. The message is :( when i trying to save
$user = $this->Users->newEntity();
if($this->request->is('post'))
{
$user = $this->Users->patchEntity($user, $this->request->data);
if($this->Users->save($user))
{
$this->Flash->success(':)');
return $this->redirect(['controller' => 'Users', 'action' => 'index']);
}
else
{
$this->Flash->error(':(');
}
debug($this->request->data);
}
$this->set(compact('user'));
this is my table , I made a migration. All fields can be null
$table = $this->table('users');
$table->addColumn('first_name','string',array('limit'=>100))
->addColumn('last_name','string',array('limit'=>100))
->addColumn('email','string',array('limit'=>100))
->addColumn('password','string')
->addColumn('role','enum',array('values'=>'admin,user'))
->addColumn('active','boolean')
->addColumn('created','datetime')
->addColumn('modified','datetime')
->create();
this is my request data
[
'first_name' => 'wewe',
'last_name' => 'wewe',
'email' => 'wewe#wee.com',
'password' => 'wewewe',
'role' => 'admin',
'active' => '1'
]
I hope that you help me , I am very frustrated
EDIT: if i use print_r ($user->errors()); i get this...
Array ( [firts_name] => Array ( [_required] => This field is required ) )
Your error is in the name of your data, the request data is
'first_name' => 'wewe'"
your column name is "firts_name", its a typing error.

Insert multiple data from other table in 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();
}

How to save data in model using Yii2 grid with Editable column

Can anyone help on editable column in gridview.I am using Yii2 and stuck with it.
I can't save data in my model.I can post from gridview column.
In my grid view:
$gridColumns= [
'patient_no',
'category_name',
'sdv_text',
[
'class' => 'kartik\grid\EditableColumn',
'attribute'=>'sdv_status',
'pageSummary' => true,
'editableOptions'=> [
'header' => 'profile',
'format' => Editable::FORMAT_BUTTON,
'inputType' => Editable::INPUT_DROPDOWN_LIST,
'data'=> $StatusList,
]
],
// 'date_sdv_performed',
[
'class' => 'kartik\grid\EditableColumn',
'attribute'=>'date_sdv_performed',
'editableOptions' => [
'header' => 'Date Sdv Performed',
'inputType'=>\kartik\editable\Editable::INPUT_WIDGET,
'format'=>\kartik\datecontrol\DateControl::FORMAT_DATE,
'widgetClass'=> 'kartik\datecontrol\DateControl',
],
],
[
'class' => 'kartik\grid\EditableColumn',
'attribute'=>'comments',
'hAlign' => 'top',
'vAlign' => 'middle',
'width'=>'100px',
'headerOptions' => ['class' => 'kv-sticky-column'],
'contentOptions' => ['class' => 'kv-sticky-column'],
'pageSummary' => true,
],
];
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'layout'=>"{items}\n{pager}",
'pjax'=>true,
'toolbar' => [
'{export}',
'{toggleData}'
],
'responsive'=>true,
'hover'=>true,
'columns' => $gridColumns
]);
In my controller action:
public function actionMonitoring($site_name)
{
$this->layout = 'sdv-carolina-main';
$Countries = new Countries;
$model = new Flagging;
$searchModel = new FlaggingSearch();
$dataProvider = $searchModel->monitoringsearch($site_name);
$allocatedsites = new AllocatedSites;
if (Yii::$app->request->post('hasEditable'))
{
$model = $this->findModel($model['flagging_id']);
$out = Json::encode(['output'=>'', 'message'=>'']);
$post = [];
$posted = current($_POST['Flagging']);
$post['Flagging'] = $posted;
if ($model->load($post)) {
$model->save();
$output = '';
if (isset($posted['sdv_status']))
{
$output = $model->sdv_status;
}
$out = Json::encode(['output'=>$output, 'message'=>'']);
}
echo $out;
return;
}
return $this->render('monitoring',
[
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'Countries' => $Countries,
'model'=>$model,
'allocatedsites' => $allocatedsites,
]);
}
The problem is I can't update my model because of I can't get the id.
I just need the id to update specific row.How can I get the id while using editable column?
Thanks in advance.
Actually the solution is easy. I just need the id of that specific row to update that.And in my ajax post I got something like this:
Flagging[0][status] NO
_csrf TlhyUm5kajAoNxgVNy0/ZCoyHApZUlNUFh0rB1gRPGoAFSIdGSAifQ==
editableIndex 0
editableKey 13
hasEditable 1
and found the editableKey is the id of that specific row!
Now in my controller I write down this code given below:
$_id=$_POST['editableKey'];
$model = $this->findModel($_id);
Here $_id is the posted editableKey value which is the id of the specific row.
and with the id I use it to get the specific model and just update data based on that id.

Resources