Import excel in laravel Array key - excel

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.');
}
}

Related

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

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

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();
}

Too few arguments to function App\Controllers\Parsys::__construct(), 0 passed in

First I code without use RequestInterface and runwell, but I when I applicate the RequestInterface from the docs here: https://codeigniter4.github.io/userguide/incoming/incomingrequest.html I got this error, What happen with my code?
<?php namespace App\Controllers;
use CodeIgniter\HTTP\RequestInterface;
class Parsys extends BaseController {
protected $request;
public function __construct(RequestInterface $request) {
$this->request = $request;
}
public function index() {
$data = [
'title' => "Parameter System",
];
return view("backend/parsys_frm", $data);
}
public function getList() {
$frm = $request->getGet('frm');
$q = $this->request->getGet('q');
$order_by = $this->request->getGet('order_by');
$page = $this->request->getGet('page');
$limit = $this->request->getGet('limit');
$limit = #$limit == 0 ? 10 : $limit;
$this->queryList($total, $current, $page, $limit, $q, [1 => 1]);
$data = $current->result_array();
header('Content-Type: application/json');
echo json_encode(compact(['total', 'page', 'limit', 'data', 'q']));
}
I use ubuntu 20.04, lampp PHP 7.4
Instead of using the __construct magic method use the built in init method.
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
}

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.

zend : Fatal error: Class 'Application_Model_User' not found

I am trying connecting to my model class defined in /application/models named user.php.
Following is how my Bootstrap looks like:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap{
protected function _initAppAutoload() {
$autoloader = new Zend_Loader_Autoloader_Resource(array(
'namespace' => 'Application',
'basePath' => APPLICATION_PATH,
'resourceTypes' => array(
'model' => array(
'path' => 'models',
'namespace' => 'Model',
)
)
));
echo '<pre>';
var_dump($autoloader);
return $autoloader;
}
}
Folling is my application.ini
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
Following is my IndexController.php
class IndexController extends Zend_Controller_Action {
private $user_connection;
private $login_status;
public function init() {
/* Initialize action controller here */
$this->user_connection = new Application_Model_User();
}
public function indexAction() {
$sql = " SELECT *
FROM USER";
$this->view->deals = $this->user_connection->select($sql);
}
following is my user.php file:
class Application_Model_User extends Application_Model_Db_Connection {
public function __construct() {
parent::__construct();
}
public function Connection(){
return $this->getConnection();
}
public function insert($data, $table = 'user'){
return parent::insert($table, $data);
}
public function select($sql){
return parent::select($sql);
}
}
Strange part is, I am developing on windows and everything runs fine, but when I push the same code to my ec2 linux instance, I get this fatal error.
Fatal error: Class 'Application_Model_User' not found in /var/www/html/dev/application/controllers/IndexController.php on line 11
I went through many questions on stack overflow and tried most of them, but I am not close to solve this problem. Any help would be appreciated.
I was able to fix the above issue, it was due to case sensitivity of linux. I renamed my models with first letter capital and was able to access them in my Controller.
user.php -> User.php
also for adding subfolder to your model you can add following to the bootstrap.
protected function _initAppAutoload() {
$autoloader = new Zend_Loader_Autoloader_Resource(array(
'namespace' => 'Application',
'basePath' => APPLICATION_PATH,
'resourceTypes' => array(
'model' => array(
'path' => 'models/',
'namespace' => 'Model_',
),
'model_db' => array(
'path' => 'models/db',
'namespace' => 'Model_Db_'
)
)
));

Resources