How to import file excel with format xlsx to Laravel 8?
I want import an excel file, i success for get data from excel. But when i run query for add data, the value is null.
I have code for import excel like this
Controller
Excel::import(new ImportItem($request->id_warrent), $request->upload);
Import
class ImportItem implements ToModel,WithHeadingRow, WithStartRow
{
public function __construct($id_warrent)
{
$this->id_warrent = $id_warrent;
}
public function model(array $row)
{
return new WarrentItemModel([
'id_warrent_item' => Str::random(5),
'warrent_entry_id' => $this->id_warrent,
'warr_item_category' => $row[0],
'warr_item_code' => $row[1],
'warr_item_nup' => $row[2],
'warr_item_name' => $row[3],
'warr_item_type' => $row[4],
'warr_item_qty' => $row[5],
'warr_item_unit' => $row[6]
]);
}
public function startRow(): int
{
return 3;
}
}
I don't know error position, when i tes $row used dd, i can get data from excel, but when i return new warrent item model, $row can't get value.
test used dd
error can't get value from excel
In your sql table you have you have a column 'warr_item_category', which default property is set to be not null, just set the property of that column to null and it will solve your problem, hope that helps
Related
I tried to make a function where User could import formatted file such as .csv or .xlsx.
I make the function using Maatwebsite excel library.
When I tried to insert the data to database, a cell that has value of today date 24/01/2023 is converted to 44950
My Import model kinda like this
public function model(array $row)
{
return new Event([
/**
* Other attributes and columns
*
*/
'date' => $row[1],
]);
}
How to convert those value to 'Y-m-d'?
I found the best solutions, idk what happened to the excel imported files, but this helps me.
use PhpOffice\PhpSpreadsheet\Shared\Date;
public function model(array $row)
{
return new Event([
/**
* Other attributes and columns
*
*/
'date' => Date::excelToDateTimeObject($row[1]),
]);
}
Source: https://github.com/SpartnerNL/Laravel-Excel/issues/1978
why get undefined offset when importing excel file to the database using laravel.
UserImport.php
public function model(array $row)
{
var_dump($row);
return new User([
'name' =>$row[0],
'email'=>$row[1],
'password' => Hash::make('password'),
]);
}
UserImportController
public function store(Request $request){
$file = $request->file('file');
Excel::import(new UsersImport, $file);
return back()->withStatus('Successfully');
}
when uploading the excel file, display it like this.
enter image description here
I used var_dump() to see the array. I entered 4 rows in the excel file. But display 5 array data. Why that??? (display in entered image.
)
I believe it is because of the new line at the end of the file.
You should check if it contains only a new line and skip the import.
set if condition for UserImport.php
if($row[0] !=""){
return new User([
'name' =>$row[0],
'email'=>$row[1],
'password' => Hash::make('password'),
]);
}
I've an excel file with following data. The below is the data of 2 users. Each user have 5 rows of details. I need to import the following to 2 rows in database.
The below is my table structure
What I need is, I need to import the excel in such a way, in the table there should be only 2 rows like below.
How can I do this in Laravel 5.8.
Here is my controller code
public function importMovementFile (Request $request){
$this->validate($request, [
'mcafile' => 'required|mimes:xls,xlsx,ods'
]);
$path = $request->file('mcafile')->getRealPath();
$data = \Excel::import(new UsersImport,$path);
return back()->with('success', 'Excel Data Imported successfully.');
}
UserImports
use Maatwebsite\Excel\Row;
use Maatwebsite\Excel\Concerns\OnEachRow;
class UsersImport implements OnEachRow
{
public function onRow(Row $row)
{
$rowIndex = $row->getIndex();
$row = $row->toArray();
UploadMovAnalysisDataFiles::create([
'member_name' => $row[0][$rowIndex],
]);
}
}
Okay I found the solution to this,
We can do this by checking the name inside a for loop. First of all, check whether the name is empty or not, if empty place the first name in name variable and loop throughout. Store each scores of the corresponding name in an object. When another name comes insert the first details and loop through the next and so on.
public function insertExcel
{
$obj= new UploadMovAnalysisDataFiles();
$name ='';
for($i=1;$i<$rows->count();$i++){
if($name==''){
$name = $rows[$i][0];
$id = $rows[$i][1];
$date = date('Y-m-d h:i:s', strtotime($rows[$i][2]));
$visit_date = $date;
//function call
score($rows[$i][3],$rows[$i][4];
}elseif($name==$rows[$i][0]){
//function call
score($rows[$i][3],$rows[$i][4];
}else{
UploadMovAnalysisDataFiles::create([
'member_name' => $name,
'mov_analysis_tag_id' => $id ,
'visit_date' => $date,
'fitness_score' => $obj->fscore,
'knee_score' => $obj->kscore,
'hip_score' => $obj->hscore,
'core_score' => $obj->cscore,
'shoulder_score' => $obj->sscore,
]);
$name = $rows[$i][0];
$id = $rows[$i][1];
$date = date('Y-m-d h:i:s', strtotime($rows[$i][2]));
$visit_date = $date;
//function call
score($rows[$i][3],$rows[$i][4]);
}
}
UploadMovAnalysisDataFiles::create([
'member_name' => $name,
'mov_analysis_tag_id' => $id ,
'visit_date' => $date,
'fitness_score' => $obj->fscore,
'knee_score' => $obj->kscore,
'hip_score' => $obj->hscore,
'core_score' => $obj->cscore,
'shoulder_score' => $obj->sscore,
]);
}
Function to keep each score in an object.
function score($rows[$i][3],$rows[$i][4){
if($rows[$i][3]== 'VSFitness_Score'){
$obj->fscore = $rows[$i][4];
}if($rows[$i][3]== 'knee_Score'){
$obj->kscore = $rows[$i][4];
}if($rows[$i][3]== 'Hip_Score'){
$obj->hscore = $rows[$i][4];
}if($rows[$i][3]== 'Core_Score'){
$obj->cscore = $rows[$i][4];
}if($rows[$i][3]== 'Shoulder_Score'){
$obj->sscore = $rows[$i][4];
}
}
I am trying to IMPORT an excel file containing some data and an error occurred
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '35492' for column 'resident_dob' at row 1
At first I was guessing that it might have been with the data in the excel file, and I've noticed that its format doesn't match the format in the SQL, So I've tried changing it but the same error have occurred. btw here's the Excel File Data
Here's the code for the Model:
public function model(array $row)
{
return new Resident([
'resident_fname' => $row[0],
'resident_lname' => $row[1],
'resident_mi' => $row[2],
'resident_dob' => $row[3],
'role' => $row[4],
'resident_age' => $row[5],
'resident_address' => $row[6],
'resident_contact' => $row[7],
'resident_email' => $row[8],
'resident_purok' => $row[9],
'resident_status' => $row[10],
'resident_gender' => $row[11],
'resident_religion' => $row[12],
'ResidentVoter_status' => $row[13],
]);
}
I really have no Idea with what to do with this Error. Can anyone help me with this? I'm still new to Laravel.
The issue is SQL doesn't support the date format you are feeding in the excel (unless chaged the default configuration)
By default SQL can store your date as 1997-03-03 00:00:00 which translates to Y-m-d H:i:s in PHP date format
So you need to manually convert it to the expected format either use DateTime or laravel's Carbon package. Below I have used Carbon
Declare this at the top
use Carbon;
And now convert the date
'resident_dob' => Carbon::parse($row[3])->format('Y-m-d H:i:s');
In my CakePHP app when I try to get data like this:
$this->loadModel('Radio');
$posts = $this->Radio->find('all');
the integers are displayed like strings (in debug) :
'Radio' => array(
'idSong' => '4',
'name' => 'batman',
'title' => 'Batman Theme Song'
),
why? the type is int in the DB. I need integers correctly displayed in my JSON files
Not sure if there's a straightforward solution, but you could change the model data using afterfind
Something like
public function afterFind($results, $primary = false) {
foreach ($results as $key => $val) {
if (isset($val['Radio']['idSong'])) {
$results[$key]['Radio']['idSong'] = (int)$results[$key]['Radio']['idSong'];
}
}
return $results;
}