noblemfd's avatar

Excel upload not getting to StudentImport file

I have this code in Laravel-8 using Maatwebsite package for Excel Upload:

Import:

namespace App\Imports;

use App\Models\Student;
use Maatwebsite\Excel\Concerns\ToModel;

class StudentImport implements ToModel
{
    public function model(array $row)
    {
        return new Student([
            'id' => rand(100000, 1000000),
            'user_id' => $row[0],
            'school_id' => $row[1],
            'class_id' => $row[2],
            'phone' => $row[3],
        ]);
     dd('hello');
    }
}

Controller:

public function import(Request $request, $user)
{
    $validator = Validator::make($request->all(), [
        'import' => 'file|mimes:xls,xlsx|max:5000',
    ]);
    if($validator->fails()) {
        return response()->json(['message' => $validator->errors()], 401);
    } else {
        $check = User::where('id', $user)->pluck('id');
        if($check[0] !== null || $check[0] !== undefined) {

            $file = $request->file('import');
            $file->move(public_path('storage/file_imports/location_imports'), $file->getClientOriginalName());
            Excel::import(new StudentImport, public_path('storage/file_imports/location_imports/' . $file->getClientOriginalName() ));
            return response()->json(['message' => 'Successfuly import data'], 200);
        } else {
            return response()->json(['message' => 'Not allowed'], 401);
        }
    }
}

When I observed that the Excel file got stored in the public_path, but not getting into the DB, so I did

dd('hello') inside App\Imports\StudentImport. I didn't see any response.

What could be the problem, and how do I resolve this?

0 likes
1 reply
thea's avatar
thea
Best Answer
Level 10

Hi @noblemfd,

First of all, your dd('hello') can't work after a return statement :P So it's normal that you can't have the hello message.

  • Maybe you could check inside the logs file if there's any error,
  • Also try without specifying anyid, Eloquent will automatically auto-increment it, this might be the reason why it doesn't seem to save to your database,

Could you share your Student Model and your database migration ? To check where the problem might occur ?

Cheers,

Please or to participate in this conversation.