英文:
Laravel import csv file failed
问题
I tried to implement an import csv file on my web. When I tried to import the csv file, the csv file is not saving into the database, and when I tried to dd()
it, it shows no errors, and not showing the result of the dd()
, but the import failed. How to resolve this issue?
The model:
namespace Modules\User\Imports;
use App\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithCalculatedFormulas;
use Spatie\Permission\Models\Role;
class VendorImport implements ToModel, WithCalculatedFormulas
{
/**
* @param Collection $collection
*/
public function model(array $row)
{
// Implement your import logic here
// dd($row);
$user = new User([
'name' => $row[0],
'first_name' => $row[1],
'last_name' => $row[2],
'email' => $row[3],
'email_verified_at' => Carbon::now()->timestamp,
'password' => $row[5],
'address' => $row[6],
'address2' => $row[7],
'phone' => $row[8],
'phone2' => $row[9],
'birthday' => $row[10],
'city' => $row[11],
'state' => $row[12],
'country' => $row[13],
'zip_code' => $row[14],
'last_login_at' => $row[15],
'avatar_id' => $row[16],
'bio' => $row[17],
'status' => $row[18],
'create_user' => $row[19],
'update_user' => $row[20],
'vendor_commission_amount' => $row[21],
'vendor_commission_type' => $row[22],
'deleted_at' => null,
'remember_token' => $row[24],
'created_at' => Carbon::now()->timestamp,
'updated_at' => Carbon::now()->timestamp,
'payment_gateway' => $row[27],
'total_guests' => $row[28],
'locale' => $row[29],
'business_name' => $row[30],
'avatar' => $row[31],
'messenger_color' => $row[32],
'dark_mode' => $row[33],
'active_status' => $row[34],
'verify_submit_status' => $row[35],
'is_verified' => $row[36],
'user_name' => $row[37],
'member' => $row[38],
'role' => $row[39],
]);
$user->save(); // Corrected method call
if ($role = Role::findById(1)) {
$user->syncRoles([$role]);
}
return $user;
}
// public function sheets(): array
// {
// return [
// 'users' => new UserImportSheet(),
// ];
// }
}
The controller:
public function import(Request $request)
{
$this->validate($request, [
'file' => 'required|mimes:csv'
]);
$file = $request->file('file');
$nama_file = rand() . $file->getClientOriginalName();
$file->move('file_vendor', $nama_file);
Excel::import(new VendorImport, public_path('/file_vendor/' . $nama_file));
return redirect()->back()->with('success', __('Upload successfully!'));
}
The route:
Route::get('/import', 'UserController@import_form')->name('user.admin.import.form');
Route::post('/import', 'UserController@import')->name('user.admin.import');
The view:
<form action="{{ route('user.admin.import') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="file">
<button type="submit">Upload Excel</button>
</form>
英文:
I tried to implement an import csv file on my web. When I tried to import the csv file, the csv file is not saving into the database, and when I tried to dd()
it, it shows no errors, and not showing the result of the dd()
, but the import failed. How to resolve this issue?
The model :
<?php
namespace Modules\User\Imports;
use App\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithCalculatedFormulas;
use Spatie\Permission\Models\Role;
class VendorImport implements ToModel, WithCalculatedFormulas
{
/**
* @param Collection $collection
*/
public function model(array $row)
{
// Implement your import logic here
//dd($row);
$user = new User([
'name' => $row[0],
'first_name' => $row[1],
'last_name' => $row[2],
'email'=> $row[3],
'email_verified_at'=> Carbon::now()->timestamp,
'password'=> $row[5],
'address'=> $row[6],
'address2'=> $row[7],
'phone'=> $row[8],
'phone2'=> $row[9],
'birthday'=> $row[10],
'city'=> $row[11],
'state'=> $row[12],
'country'=> $row[13],
'zip_code'=> $row[14],
'last_login_at'=> $row[15],
'avatar_id'=> $row[16],
'bio'=> $row[17],
'status'=> $row[18],
'create_user'=> $row[19],
'update_user'=> $row[20],
'vendor_commission_amount'=> $row[21],
'vendor_commission_type'=> $row[22],
'deleted_at'=> null,
'remember_token'=> $row[24],
'created_at'=> Carbon::now()->timestamp,
'updated_at'=> Carbon::now()->timestamp,
'payment_gateway'=> $row[27],
'total_guests'=> $row[28],
'locale'=> $row[29],
'business_name'=> $row[30],
'avatar'=> $row[31],
'messenger_color'=> $row[32],
'dark_mode'=> $row[33],
'active_status'=> $row[34],
'verify_submit_status'=> $row[35],
'is_verified'=> $row[36],
'user_name'=> $row[37],
'member'=> $row[38],
'role'=> $row[39],
]);
$user->save(); // Corrected method call
if ($role = Role::findById(1)) {
$user->syncRoles([$role]);
}
return $user;
}
// public function sheets(): array
// {
// return [
// 'users' => new UserImportSheet(),
// ];
// }
}
The controller :
public function import(Request $request)
{
$this->validate($request, [
'file' => 'required|mimes:csv'
]);
$file = $request->file('file');
$nama_file = rand() . $file->getClientOriginalName();
$file->move('file_vendor', $nama_file);
Excel::import(new VendorImport, public_path('/file_vendor/' . $nama_file));
return redirect()->back()->with('success', __('Upload successfully!'));
}
The route :
Route::get('/import', 'UserController@import_form')->name('user.admin.import.form');
Route::post('/import', 'UserController@import')->name('user.admin.import');
The view :
<form action="{{ route('user.admin.import') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="file">
<button type="submit">Upload Excel</button>
</form>
答案1
得分: 1
I have debug and looks like execution stops in import method at UserController.
public function import(Request $request)
{
$this->validate($request, [
'file' => 'required|mimes:csv'
]);
}
You execution is not processing after validate csv file please try to remove mimes:csv from the validating because of csv return always txt mime.
One more thing please use public_path() instead of absolute path I have changed code i.e. $file->move(public_path()."/file_vendor/", $nama_file); and check in directory is there csv file uploading successfully or not if yes then you can check in dd(). Please check attached image.
Good Luck!
英文:
I have debug and looks like execution stops in import method at UserController.
public function import(Request $request)
{
$this->validate($request, [
'file' => 'required|mimes:csv'
]);
}
You execution is not processing after validate csv file please try to remove mimes:csv from the validating because of csv return always txt mime.
One more thing please use public_path() instead of absolute path I have changed code i.e. $file->move(public_path()."/file_vendor/", $nama_file); and check in directory is there csv file uploading successfully or not if yes then you can check in dd(). Please check attached image.
Good Luck!
答案2
得分: 0
如果你没有达到dd()
,可能会在验证阶段卡住(状态码422)。
尝试将验证更改为'required|mimes:csv,txt'
(将接受txt文件),或者尝试移除mimes
验证以确定问题。如果这是解决方案,你可以尝试验证文件扩展名以避免上传.txt
文件(可能需要自定义验证规则)。
即使在调用types方法时只需要指定扩展名,该方法实际上通过读取文件内容并猜测其MIME类型来验证文件的MIME类型。
https://laravel.com/docs/10.x/validation#validating-files-file-types
关于CSV验证问题的更多信息:
https://stackoverflow.com/a/62585014/22367649
英文:
If you don't reach the dd()
it probably get stuck at validation (status code 422).
Try to change the validation to 'required|mimes:csv,txt'
(will accept txt-files) or just try to remove mimes
validation to identify the issue. If this would be the solution, you could try to also validate the file extension to avoid .txt
uploads (probably requires custom validation rule).
> Even though you only need to specify the extensions when invoking the types method, this method actually validates the MIME type of the file by reading the file's contents and guessing its MIME type.
https://laravel.com/docs/10.x/validation#validating-files-file-types
More about CSV-validation issue:
https://stackoverflow.com/a/62585014/22367649
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论