Reputation: 2072
I want to upload a csv file using Maatwebsite\Excel
. When i'm uploading an Excel
file it works fine but when i'm trying to upload a csv file i'm having an error Undefined offset: 1
.
The problem i think is with the delimiter of the csv file (Where the delimiter is a ;
), when i var_dump($row)
of the excel file i have this result array(3) { [0]=> string(8) "user1CSV" [1]=> string(11) "[email protected]" [2]=> string(9) "azerty&23" }
but with the csv file the result is array(1) { [0]=> string(31) "user1CSV;[email protected];azerty&23" }
.
How can i set the delimiter to accept Excel
and Csv
delimiters? My code is :
The controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\UsersImport;
class UserController extends Controller
{
/**
* @return \Illuminate\Support\Collection
*/
public function fileImportExport()
{
return view('file-import');
}
/**
* @return \Illuminate\Support\Collection
*/
public function fileImport(Request $request)
{
Excel::import(new UsersImport, $request->file('file')->store('temp'));
return back();
}
}
The import class
class UsersImport implements ToModel
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
var_dump($row);
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => Hash::make($row[2])
]);
}
}
Upvotes: 0
Views: 1954
Reputation: 1280
In your config/excel.php
file you can set delimiter
in csv
array as ;
You can check full config/excel.php
file here: https://github.com/Maatwebsite/Laravel-Excel/blob/3.1/config/excel.php
And on line 45 there is a csv.delimiter
setting, set ,
by default. You just need to change it to ;
https://github.com/Maatwebsite/Laravel-Excel/blob/3.1/config/excel.php#L45
If you want to set custom csv settings for each of your Import class; as I can see from Laravel Excel documentation you can set custom csv delimiter: https://docs.laravel-excel.com/3.1/imports/custom-csv-settings.html#available-settings
In your app\Imports\UsersImport.php
file you can set your delimiter
as ;
by adding this method:
public function getCsvSettings(): array
{
return [
'delimiter' => ";"
];
}
Upvotes: 1