Created
June 28, 2024 09:55
-
-
Save rizkhal/d66ddd636dc763d7c7f612b7430c8969 to your computer and use it in GitHub Desktop.
Laravel Excel import validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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