skip to Main Content

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 ModulesUserImports;

use AppUser;
use CarbonCarbon;
use IlluminateSupportFacadesHash;
use IlluminateSupportFacadesValidator;
use IlluminateSupportFacadesDB;
use MaatwebsiteExcelConcernsToModel;
use MaatwebsiteExcelConcernsWithCalculatedFormulas;
use SpatiePermissionModelsRole;

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>

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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.

    enter image description here

    Good Luck!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search