Laravel 导入 CSV 文件失败

huangapple go评论89阅读模式
英文:

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 :

&lt;?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([
&#39;name&#39; =&gt; $row[0],
&#39;first_name&#39; =&gt; $row[1],
&#39;last_name&#39; =&gt; $row[2],
&#39;email&#39;=&gt; $row[3],
&#39;email_verified_at&#39;=&gt; Carbon::now()-&gt;timestamp,
&#39;password&#39;=&gt; $row[5],
&#39;address&#39;=&gt; $row[6],
&#39;address2&#39;=&gt; $row[7],
&#39;phone&#39;=&gt; $row[8],
&#39;phone2&#39;=&gt; $row[9],
&#39;birthday&#39;=&gt; $row[10],
&#39;city&#39;=&gt; $row[11],
&#39;state&#39;=&gt; $row[12],
&#39;country&#39;=&gt; $row[13],
&#39;zip_code&#39;=&gt; $row[14],
&#39;last_login_at&#39;=&gt; $row[15],
&#39;avatar_id&#39;=&gt; $row[16],
&#39;bio&#39;=&gt; $row[17],
&#39;status&#39;=&gt; $row[18],
&#39;create_user&#39;=&gt; $row[19],
&#39;update_user&#39;=&gt; $row[20],
&#39;vendor_commission_amount&#39;=&gt; $row[21],
&#39;vendor_commission_type&#39;=&gt; $row[22],
&#39;deleted_at&#39;=&gt; null,
&#39;remember_token&#39;=&gt; $row[24],
&#39;created_at&#39;=&gt; Carbon::now()-&gt;timestamp,
&#39;updated_at&#39;=&gt; Carbon::now()-&gt;timestamp,
&#39;payment_gateway&#39;=&gt; $row[27],
&#39;total_guests&#39;=&gt; $row[28],
&#39;locale&#39;=&gt; $row[29],
&#39;business_name&#39;=&gt; $row[30],
&#39;avatar&#39;=&gt; $row[31],
&#39;messenger_color&#39;=&gt; $row[32],
&#39;dark_mode&#39;=&gt; $row[33],
&#39;active_status&#39;=&gt; $row[34],
&#39;verify_submit_status&#39;=&gt; $row[35],
&#39;is_verified&#39;=&gt; $row[36],
&#39;user_name&#39;=&gt; $row[37],
&#39;member&#39;=&gt; $row[38],
&#39;role&#39;=&gt; $row[39],
]);
$user-&gt;save(); // Corrected method call
if ($role = Role::findById(1)) {
$user-&gt;syncRoles([$role]);
}
return $user;
}
// public function sheets(): array
// {
//     return [
//         &#39;users&#39; =&gt; new UserImportSheet(),
//     ];
// }
}

The controller :

public function import(Request $request)
{
$this-&gt;validate($request, [
&#39;file&#39; =&gt; &#39;required|mimes:csv&#39;
]);
$file = $request-&gt;file(&#39;file&#39;);
$nama_file = rand() . $file-&gt;getClientOriginalName();
$file-&gt;move(&#39;file_vendor&#39;, $nama_file);
Excel::import(new VendorImport, public_path(&#39;/file_vendor/&#39; . $nama_file));
return redirect()-&gt;back()-&gt;with(&#39;success&#39;, __(&#39;Upload successfully!&#39;));
}

The route :

Route::get(&#39;/import&#39;, &#39;UserController@import_form&#39;)-&gt;name(&#39;user.admin.import.form&#39;);
Route::post(&#39;/import&#39;, &#39;UserController@import&#39;)-&gt;name(&#39;user.admin.import&#39;);

The view :

&lt;form action=&quot;{{ route(&#39;user.admin.import&#39;) }}&quot; method=&quot;POST&quot; enctype=&quot;multipart/form-data&quot;&gt;
@csrf
&lt;input type=&quot;file&quot; name=&quot;file&quot;&gt;
&lt;button type=&quot;submit&quot;&gt;Upload Excel&lt;/button&gt;
&lt;/form&gt;

答案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.

Laravel 导入 CSV 文件失败

Good Luck!

英文:

I have debug and looks like execution stops in import method at UserController.

public function import(Request $request)
{        
$this-&gt;validate($request, [
&#39;file&#39; =&gt; &#39;required|mimes:csv&#39;
]);
}

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.

Laravel 导入 CSV 文件失败

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 &#39;required|mimes:csv,txt&#39; (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

huangapple
  • 本文由 发表于 2023年8月10日 12:24:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76872640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定