noblemfd's avatar

Maatwebsite Excel import stored in storage only but not in DB

I am importing Excel File using Laravel-8 endpoints and Maatwebsite-3.1 package.

The way I did it is that, the Uploaded Excel file will first get to the storage (storage/file_imports/student_imports). Then Laravel pickes it up from there, stores it into the DB table through StudentImport using Maatwebsites.

StudentImport:

<?php

  namespace App\Imports;

  use App\Models\User;
  use App\Models\Student;
  use Illuminate\Support\Facades\Hash;
  use Illuminate\Support\Facades\DB;
  use Illuminate\Support\Str;
  use Illuminate\Support\Facades\Auth;
  use Illuminate\Support\Facades\Password;
  use Illuminate\Validation\Rule;
  use Maatwebsite\Excel\Concerns\ToModel;
  use Maatwebsite\Excel\Concerns\Importable;
  use Maatwebsite\Excel\Concerns\WithBatchInserts;
  use Maatwebsite\Excel\Concerns\WithValidation;
  use Maatwebsite\Excel\Concerns\WithHeadingRow;
  use Maatwebsite\Excel\Concerns\SkipsErrors;
  use Maatwebsite\Excel\Concerns\SkipsOnError;
  use Maatwebsite\Excel\Concerns\SkipsFailures;
  use Maatwebsite\Excel\Concerns\SkipsOnFailure;
  use Illuminate\Support\Facades\Validator;
  use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
  use Maatwebsite\Excel\Validators\Failure;
  use Throwable;

class StudentImport implements
  ToModel,
  WithValidation,
  WithHeadingRow,
  SkipsOnError,
  SkipsOnFailure,
  WithBatchInserts
{
protected $companyId;

public function __construct()
{
    $this->companyId = Auth::user()->company_id;
}

use Importable, SkipsErrors, SkipsFailures;

public function model(array $row)
{
    $student_data = [
        'first_name'                        => $row[0],
        'other_name'                        => $row[1] ?? '',
        'last_name'                         => $row[2],
        'email'                             => preg_replace('/\s+/', '', strtolower($row[3])),
        'gender'                            => $row[4],
        'nationality_id'                    => $this->getNationality() ?? '',
        'school_id'                        => Auth::user()->school_id,
    ];
    $student = Student::create($student_data);

    if (User::where('email', '=', $student->email)->exists()) {
        $user = User::update([
            'first_name'                        => $student->first_name,
            'other_name'                        => $student->other_name,
            'last_name'                         => $student->last_name,
            'complete_profile'                  => 1,
            'active'                            => 1,
            'user_type'                         => 'Driver',
            'company_id'                        => Auth::user()->company_id,
            'updated_at'                        => date("Y-m-d H:i:s"),
            'updated_by'                        => Auth::user()->id,
        ]);
     }else{
        $user = User::create([
            'email'                             => $student->email,
            'username'                          => strtok($row[3], '@'),
            'password'                          => bcrypt("123456"),
            'first_name'                        => $student->first_name,
            'other_name'                        => $student->other_name,
            'last_name'                         => $student->last_name,
            'activation_token'                  => str_random(10),
        ]);
     }
}

public function headingRow(): int
{
    return 1;
}

public function getRowCount(): int
{
    return $this->rows;
}

public function customValidationAttributes()
{
    return [
        '0'     => 'First Name',
        '1'     => 'Other Name',
        '2'     => 'Last Name',
        '3'     => 'Email',
        '4'     => 'Gender',
    ];
}

public function rules(): array
{
    return [
        '*.0' => [
            'required',
            'string',
            'max:50'
        ],
        '*.1' => [
            'nullable',
            'string',
            'max:50'
        ],
        '*.2' => [
            'required',
            'string',
            'max:50'
        ],
        '*.3' => [
            'required',
            'email',
            'max:100',
            Rule::unique('studentss')->where(function ($query) {
                return $query->where('school_id', Auth::user()->school_id);
            })
        ],
        '*.4' => [
            'required',
            'string',
            'max:20'
        ],
    ];
}

public function batchSize(): int
{
    return 1000;
}

public function chunkSize(): int
{
    return 1000;
}

public function onFailure(Failure ...$failures)
{
    // Handle the failures how you'd like.
}

public function customValidationMessages()
{
    return [
        '1.in' => 'Custom message for :attribute.',
        'nim.unique' => 'Custom message',
    ];
}
}

Controller:

public function importStudent(Request $request)
{
try {
    $user = Auth::user()->id;
    $validator = Validator::make($request->all(), [
        'document' => 'file|mimes:xlsx|max:10000',
    ]);
    if($validator->fails()) {
        return $this->error($validator->errors(), 401);
    } else {
        $check = User::where('id', $user)->pluck('id');
        if($check[0] !== null || $check[0] !== undefined) {

            $file = $request->file('document');
            $file->move(public_path('storage/file_imports/student_imports'), $file->getClientOriginalName());
            Excel::import(new StudentImport, public_path('storage/file_imports/student_imports/' . $file->getClientOriginalName() ));
            return $this->success('Students Successfully Imported.', [
                'file'         => $file
            ]);
        } else {
            return $this->error('Not allowed', 401);
        }
    }
    } catch(\Exception $e) {
        return $this->error($e->getMessage());
    }
}

As I stated earlier it will first store the Excel file into:

storage/file_imports/student_imports

Then pick it from there and store in the DB.

This code is in the controller above.

The file is store in the

public/storage/file_imports/student_imports

as expected, but nothing is found in the DB. Yes it displays Success with no error.

What could be the problem and how do I resolve it?

Thanks

0 likes
0 replies

Please or to participate in this conversation.