To show validation error messages when importing data from a CSV file in Filament, you can use Laravel's built-in validation features within your import process. Assuming you are using Laravel Excel for the import, you can handle the validation within the model() method of your import class.
Here's an example of how you might set up your import class with validation:
use App\Models\Country;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Maatwebsite\Excel\Concerns\SkipsFailures;
use Illuminate\Validation\Rule;
class CountriesImport implements ToModel, WithValidation, SkipsOnFailure
{
use Importable, SkipsFailures;
public function model(array $row)
{
// Assuming the first column of your CSV is the country name
$countryName = $row[0];
// You can perform additional logic here if needed
// Return a new instance of your Country model
return new Country([
'name' => $countryName,
]);
}
public function rules(): array
{
return [
// Specify the validation rules for each column
'0' => 'required|unique:countries,name',
];
}
public function onFailure(Failure ...$failures)
{
// Handle the failures here
// You can log the errors or return them to the user
foreach ($failures as $failure) {
$failure->row(); // row that went wrong
$failure->attribute(); // either heading key (if using heading row concern) or column index
$failure->errors(); // Actual error messages from Laravel validator
$failure->values(); // The values of the row that has failed.
}
}
}
In your controller or wherever you handle the import, you can catch the validation errors and return them to the user:
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\CountriesImport;
public function import(Request $request)
{
$import = new CountriesImport;
// Handle the import
Excel::import($import, $request->file('your_csv_file'));
// Get the failures from the import
$failures = $import->failures();
if (count($failures) > 0) {
// There were failures, redirect back with the errors
return back()->withFailures($failures);
}
// Import was successful
return back()->withSuccess('Countries imported successfully!');
}
In your view, you can then display the error messages to the user:
@if(session()->has('failures'))
<div class="alert alert-danger">
<ul>
@foreach(session()->get('failures') as $validationError)
<li>Row {{ $validationError->row() }}: {{ implode(', ', $validationError->errors()) }}</li>
@endforeach
</ul>
</div>
@endif
This example assumes you're using Laravel Excel for CSV import and that you have a countries table with a name column that should be unique. Adjust the column index and validation rules according to your CSV structure and requirements.