why when import excel, my data I added is not saved to the database used laravel - excel

why when import excel, my data I added is not saved to the database ?
i import excel with type xlsx
My controller
public function importDataPegawai(Request $request)
{
Excel::import(new ImportPegawai, $request->file('upload-pegawai'));
return redirect('dashboard-admin')->with('success','Berhasil Upload Data Pegawai');
}
My Import
<?php
namespace App\Imports;
use App\Models\PegawaiModel;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Auth;
use DB;
class ImportPegawai implements ToModel, WithStartRow
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
foreach ($row as $data){
$data = DB::table('tbl_pegawai')->where('nip', $row[0])->get();
if (empty($data)) {
return new PegawaiModel([
'nip' => $row[0],
'nama_lengkap' => $row[1],
'pangkat' => $row[2],
'gol' => $row[3],
'jabatan' => $row[4],
'unit_kerja' => $row[5]
]);
}
}
}
public function startRow(): int
{
return 3;
}
}
When i dd($data) the result is like this
result dd
i got the data from my excel upload.
What's the problem ? why my data cannot save in the database

This code will return an Collection, which is an object, objects are always not empty.
DB::table('tbl_pegawai')->where('nip', $row[0])->get();
If you switch to first() it will return a model or null, effectively doing what you intended to.
DB::table('tbl_pegawai')->where('nip', $row[0])->first();

I have been in this situation before and figured that it can be caused by different factors. You might want to try the following:
Save the file you're about to upload to Excel 97-2003 Workbook format first.
Make sure the columns you're inserting data into is included in protected $fillable under App\PegawaiModel.
If certain cells in your spreadsheet are empty, make a validation for it.
Ex.
if ($row[0] === null) {
$row = null;
}
or if it's a string column that's not nullable, you can do
if ($row[0] === null) {
$row = 'NO DATA';
}

Related

LARAVEL 9: How to export data to excel based on filter data (id, month and years) using maatwebsite

I'm making an export data to excel based on employee_id filter, month and year of absence:
.
when the filter is submitted the data appears in the table below:
I have managed to get the data, but when the Download Excel button is clicked, the contents are just empty Excel, like this:
the data does not enter the excel.
My Controller:
public function rekapabsensiExcel(Request $request)
{
$idkaryawan = $request->id_karyawan;
$bulan = $request->query('bulan',Carbon::now()->format('m'));
$tahun = $request->query('tahun',Carbon::now()->format('Y'));
// simpan session
$idkaryawan = $request->session()->get('idkaryawan');
$bulan = $request->session()->get('bulan');
$tahun = $request->session()->get('tahun',);
// dd($idkaryawan,$bulan,$tahun );
if(isset($idkaryawan) && isset($bulan) && isset($tahun))
{
$data = Absensi::where('id_karyawan', $idkaryawan)
->whereMonth('tanggal', $bulan)
->whereYear('tanggal',$tahun)
->get();
// dd($data);
}else{
$data = Absensi::all();
}
return Excel::download(new RekapabsensiExport(['data'=>$data, 'idkaryawan'=>$idkaryawan]),'rekap_absensi_bulanan.xlsx');
}
My RekapAbsensiExport.php:
<?php
namespace App\Exports;
use App\Models\Absensi;
use Maatwebsite\Excel\Concerns\FromCollection;
class RekapabsensiExport implements FromCollection
{
protected $id_karyawan;
// function __construct($id_karyawan) {
// $this->id_karyawan = $id_karyawan;
// }
public function headings(): array {
return [
"No. ID","ID Karyawan","NIK","Tanggal","Jam Kerja","Jam Masuk","Jam Pulang",
"Scan Masuk","Scan Pulang","Normal","Riil","Terlambat","Plg Cepat","Absent",
"Lembur","Jml Jam Kerja","pengecualian","Harus C/I","Harus C/O","Departemen",
"Hari Normal","Akhir Pekan","Hari Libur","Jml Kehadiran","Lembur Hari Normal",
"Lembur Akhir Pekan","Lembur Hari Libur"
];
}
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return Absensi::where('id_karyawan',$this->id_karyawan)->get();
}
}
What part did I go wrong? Please help
Currently, you get no response to this statement because $this->id_karyawan is null as you have not properly passed the value through.
return Absensi::where('id_karyawan', $this->id_karyawan)->get();
Above, you are passing an array of values to the Export class. But your commented-out constructor function is only configured to accept a single parameter. If we stick to single parameters, you could do something like this.
return Excel::download(new RekapabsensiExport($data, $idkaryawan),'rekap_absensi_bulanan.xlsx');
Then your export constructor would look like this.
protected $data;
protected $id_karyawan;
function __construct($data, $id_karyawan) {
$this->data = $data;
$this->id_karyawan = $id_karyawan;
}

Import excel in laravel Array key

I am trying to upload the file but when I give import I get the following error Undefined array key "idEvento"
When I handle it by number that I start from scratch I do not get any error and insert into the database
Event Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Eventos extends Model
{
use HasFactory;
protected $fillable = [
'nombre',
'idEvento',
'idSede',
'inicio',
'fin',
'idModalidad',
'cupo',
'valor',
];
}
Import data function
public function importData(Request $request){
$file = $request->file('documento');
$validator = Validator::make(
array(
'file' => $file,
),
array(
'file' => 'file|max:5000|mimes:xlsx,xls',
)
);
if ($validator->fails()) {
return Redirect::to('conferencia/import');
}
$import = new EventosImport();
Excel::import($import, request()->file('documento'));
return view('conferencias.import', ['numRows'=>$import->getRowCount()]);
//return redirect()->to(url('conferencia'));
}
Event import code
<?php
namespace App\Imports;
use App\Models\Eventos;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class EventosImport implements ToModel, WithHeadingRow
{
private $numRows = 0;
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
++$this->numRows;
return new Eventos([
'nombre' => $row['nombre'],
'idEvento' => $row['idEvento'],
'idSede' => $row['idSede'],
'inicio' => \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row['inicio']),
'fin' => \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row['fin']),
'idModalidad' => $row['idModalidad'],
'cupo' => $row['cupo'],
'valor' => $row['valor'],
]);
}
public function getRowCount(): int
{
return $this->numRows;
}
}
Image of the excelenter image description here
it´s better than you use your function import in your controller instead of in your model. To read excel use sometimes similary to:
$data = Excel::load($path, function($reader) {})->get();
if(!empty($data) && $data->count()){
foreach ($data->toArray() as $key => $value) {
if(!empty($value)){
foreach ($value as $v) {
$insert[] = ['title' => $v['title'], 'description' => $v['description']];
}
}
}
if(!empty($insert)){
Item::insert($insert);
return back()->with('success','Insert Record successfully.');
}
}

Builder could not be converted to string

Need help, I want to sum one column in codeigniter4 but I get this error:
Error: object of class CodeIgniter\Database\MySQLi\Builder could not be converted to string
This is my model:
public function tot_crew_wni_arr() {
return $this->db->table('tbl_est_arr')->selectSum('crew_wni_arr');
}
at controller
$data = array(
'tot_crew_wni_arr' => $this->Model_home->tot_crew_wni_arr(),
);
return view('layout/v_wrapper', $data);
This is my view:
<h3><?= $tot_crew_wni_arr ?></h3>
Your model function should look something like this:
public function tot_crew_wni_arr() {
$db = \Config\Database::connect();
$builder = $db->table('tbl_est_arr');
return $builder->selectSum('crew_wni_arr')->get();
}

Querying with the Query Builder

I'M USING SYMFONY 4.12 I'm trying to write queries to filter my jobs(I've job table ,départements one) I first try with experience but I'm stuck in
here is my offerController:
/**
* #Route("/offres", name="offres")
* #param Request $request
* #param PaginatorInterface $paginator
* #param FormFactoryInterface $formFactory
* #return Response
*/
public function offreSearch(Request $request, PaginatorInterface $paginator ,FormFactoryInterface $formFactory):Response
{
$datas =new OffreEmploi();
$formFilter=$formFactory->create(OfferFilterForm::class,$datas);
$offres = $this->repository->findSearch($datas);
$formFilter->handleRequest($request);
return $this->render('offre/index.html.twig', [
'controller_name' => 'OffreController',
'offres' => $offres,
'formulaire' =>$formFilter->createView(),
]);
}
and this is my query in the offerRepository:
public function findSearch(OffreEmploi $data):?array
{
$query = $this->createQueryBuilder('o');
if ($data->getExperience() !== null) {
$query
->where('o.experience > :experience')
->setParameter('experience', $data->getExperience());
}
return $query->getQuery()->getResult();
}
when it come to enter any number IT gives the same thing it shows all the jobs stored in the database,I don't know where the problem is.
THE RESULT
Try with this solution:
public function findSearch(OffreEmploi $data):?array
{
$query = $this->createQueryBuilder('o');
if (!empty($data->getExperience())
// ...
}
return $query->getQuery()->getResult();
}
If it doesn't work , try to dump $data->getExperience() to see its value
public function findSearch(OffreEmploi $data):?array
{
$query = $this->createQueryBuilder('o');
dd($data->getExperience()) ;
}
EDIT
So try to do like this but be sure you send the form with GET method not POST:
public function offreSearch(Request $request, PaginatorInterface $paginator)
{
$em = $this->getDoctrine()->getManager();
$form = $this->createForm(OfferFilterForm::class);
$form->handleRequest($request);
$data = $request->query->all();
$qb = $em->getRepository(OffreEmploi::class)->findSearch($data);
$offres = $paginator->paginate($qb, $request->query->get('page', 1), 20);
return $this->render('offre/index.html.twig', array(
'formulaire' =>$form->createView(),
'offres' => $offres,
));
}
In the formType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('experience', IntegerType::class);
//.....
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => null,
'csrf_protection' => false,
));
}
public function getBlockPrefix()
{
return null;
}
and in the Repository:
public function findSearch($data)
{
$query = $this->createQueryBuilder('o');
if (!empty($data['experience'])) {
$query
->where('o.experience > :experience')
->setParameter('experience', $data['experience']);
}
return $query->getQuery()->getResult();
}
I think I found the answer but I just create another class witch contain all the form's field and that's it I don't know how it works because I didn't change significant things for that thinks for your help.

How do I make the has_many selector drag and drop sortable with fuelCMS 1.4?

I have created a model and added the $has_many for selecting multiple products. This is working fine but I am unable to make the selected products sortable by drag and drop. I know this is possible I have seen it. But I am unable to find anything in the documentation that shows how to get this done. Here is my model:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
require_once(FUEL_PATH.'models/Base_module_model.php');
/**
* This model handles setting up the form fields for our contact form
*
*/
class Products_category_model extends Base_module_model {
public $required = array('name', 'published');
public $has_many = array('products' => array(FUEL_FOLDER => 'Products_model'));
function __construct()
{
parent::__construct('w_product_categories');
}
/*
This will provide the list of records for display in the Admin Panel
Note how the "excerpt" will display, but truncated
Because we are using some MySQL functions in our select statement,
we pass FALSE in as the second parament to prevent CI auto escaping of fields
*/
function list_items($limit = null, $offset = null, $col = 'name', $order = 'asc', $just_count = false)
{
$this->db->select('id, name, published', FALSE);
$data = parent::list_items($limit, $offset, $col, $order);
return $data;
}
function form_fields($values = array(), $related = array())
{
$fields = parent::form_fields($values, $related);
return $fields;
}
}
class Product_category_model extends Base_module_record {
}
So it is very simple I discovered. I added this in the form fields function:
// Makes the has many drag and drop sortable.
$fields['products']['sorting'] = TRUE;
$fields['products']['after_html'] = "<div style=\"clear:both;font-style:italic\">NOTE: you can sort selected product to your choosing by clicking on the product and then dragging it into the desired placement in the list</div>";

Resources