I’m working on a Laravel V9.0 application where I need to import user data from an Excel file into a PostgreSQL database. I have set up the import functionality using the Maatwebsite Excel package. However, when I submit the form to upload the file, it redirects me to the default page of Laravel application, and I don’t see any import results or error messages(When im using Postman).
When i use blade.php view it returns Users imported successfully!.When i check the table in my postgresql i find it either empty or only one instance and it is null.
//UsersController.php:
public function importUsers(Request $request)
{
$request->validate([
'file' => 'required|mimes:xlsx,csv'
]);
Excel::import(new UsersImport, $request->file('file'));
return back()->with('success', 'Users imported successfully!');
}
//UsersImport.php
<?php
namespace App\Imports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Collection;
class UsersImport implements ToCollection, WithHeadingRow
{
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
if (empty($row['Matricule'])) {
continue;
}
User::updateOrCreate(
[
'matricule' => $row['Matricule'],
],
[
'id_badge' => $row['Badge'] ?? null,
'nom' => $row['Nom'] ?? null,
'prenom' => $row['Prenom'] ?? null,
'post' => $row['Departement'] ?? null,
'role' => $row['Role'] ?? '1',
'id_projet' => $row['Project Id'] ?? null,
]
);
}
}
}
//migration table for users:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('id_projet');
$table->integer('id_badge')->unique()->nullable();
$table->string('matricule');
$table->string('nom')->nullable();
$table->string('prenom')->nullable();
$table->string('post')->nullable();
$table->enum('role',['0','1'])->default('1')->nullable();
$table->foreign('id_projet')->references('id')->on('projects');
$table->rememberToken();
$table->timestamps();
});
Route::post('/import-users', [UsersController::class, 'importUsers'])->name('import.users');
//excel form:
[enter image description here](https://i.sstatic.net/rfItZBkZ.png)