Skip to content

Instantly share code, notes, and snippets.

@rizkhal
Created June 28, 2024 09:55
Show Gist options
  • Save rizkhal/d66ddd636dc763d7c7f612b7430c8969 to your computer and use it in GitHub Desktop.
Save rizkhal/d66ddd636dc763d7c7f612b7430c8969 to your computer and use it in GitHub Desktop.
Laravel Excel import validation
<?php
namespace App\Http\Controllers\Student;
use App\Http\Controllers\Controller;
use App\Http\Requests\Student\ImportRequest;
use App\Imports\Student\ImportExcel;
use Maatwebsite\Excel\Validators\ValidationException;
use Illuminate\Validation\ValidationException as IlluminateValidationException;
class ImportController extends Controller
{
/**
* Handle the incoming request.
*/
public function __invoke(ImportRequest $request)
{
try {
$file = $request->file('file')->store('students');
$path = storage_path("app/{$file}");
(new ImportExcel)->import($path);
return back()->success(__('Berhasil mengimpor peserta didik'));
} catch (ValidationException $e) {
$messages = collect($e->failures())->map(function ($failure) {
return "Terjadi kesalahan pada baris {$failure->row()}. {$failure->errors()[0]}";
});
throw IlluminateValidationException::withMessages([
'file' => $messages->toArray(),
]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment