Maatwebsite Rules Validation Failed on Import Data from Excel File on Laravel 10

Recently, I have been working on the project that needs to enable users to import data using the excel template file. I provided the excel file which contains the header like as the followings :

  • name_title_code -> The code of name title Ex. 003 for Ms.
  • fname -> First Name
  • lname -> Last Name
  • gender -> Gender when you were born
  • citizen_id -> The Citizen ID on the ID Card
  • registered_address -> The place you were born
  • mailing_address -> The current address that can use to contact you
  • is_same_address -> Ask whether the mailing address is the same as registered address
  • is_current_outside_country -> Ask whether currently live in the country or others

The type of value will be as shown :

  • name_title_code -> 3 digits number with leading zero(s)
  • fname -> string/text
  • lname -> string/text
  • gender -> F for Female and M for Male
  • citizen_id -> 13 digits number
  • registered_address -> string/text
  • mailing_address -> string/text
  • is_same_address -> boolean either 1 for true or 0 for false
  • is_current_outside_country -> boolean either 1 for true or 0 for false

I’m using Maatwebsite. I had created model for importing data from Excel with this command line : ‘php artisan make:import ImportUser’ and get ‘ImportUser’ under ‘AppImportsImportUser’ in Laravel Folder. The followings are my code in the ImportUser.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> <?php
namespace AppImports;
use IlluminateValidationRule;
use MaatwebsiteExcelConcernsToModel;
use MaatwebsiteExcelConcernsImportable;
use MaatwebsiteExcelConcernsWithStartRow;
use MaatwebsiteExcelConcernsWithHeadingRow;
use MaatwebsiteExcelConcernsWithValidation;
use MaatwebsiteExcelConcernsSkipsEmptyRows;
use IlluminateSupportCollection;
use MaatwebsiteExcelConcernsToCollection;
use Auth;
use AppModelsUser;
class ImportedStudentProfile implements ToModel, WithStartRow, WithHeadingRow, WithValidation, SkipsEmptyRows, ToCollection
{
use Importable;
public function model(array $row)
{
// Define Each Row
return new User([
'name_title_code' => $row['name_title_code'],
'lname' => $row['lname'],
'gender' => $row['gender'],
'citizen_id' => $row['citizen_id'],
'registered_address' => $row['registered_address'],
'mailing_address' => $row['mailing_address],
'is_same_address' => $row['is_same_address'],
'is_current_outside_country' => $row['is_current_outside_country'],
'created_at' => CarbonCarbon::now(),
'created_by' => Auth::user()->id,
'updated_at' => CarbonCarbon::now(),
'updated_by' => Auth::user()->id,
]);
}
public function startRow():int
{
// Skip The First Row as Header
return 2;
}
public function rules(): array
{
return [
'name_title_code' => ['required', Rule::exists('name_title', 'code')],
'fname' => 'required',
'lname' => 'required',
'gender' => ['required', Rule::in('F', 'M')],
'citizen_id' => ['required', digits:13, Rule::unique('users', 'citizen_id')],
'registered_address' => 'required',
'mailing_address' => [Rule::requiredIf('is_same_address', 0)],
'is_same_address' => ['required', 'boolean'],
'is_current_outside_country' => ['required', 'boolean', Rule::declinedIf('is_same_address', 1)],
'*.name_title_code' => ['required', Rule::exists('name_title', 'code')],
'*.fname' => 'required',
'*.lname' => 'required',
'*.gender' => ['required', Rule::in('F', 'M')],
'*.citizen_id' => ['required', digits:13, Rule::unique('users', 'citizen_id')],
'*.registered_address' => 'required',
'*.mailing_address' => [Rule::requiredIf('is_same_address', 0)],
'*.is_same_address' => ['required', 'boolean'],
'*.is_current_outside_country' => ['required', 'boolean', Rule::declinedIf('is_same_address', 1)],
];
}
}
</code>
<code> <?php namespace AppImports; use IlluminateValidationRule; use MaatwebsiteExcelConcernsToModel; use MaatwebsiteExcelConcernsImportable; use MaatwebsiteExcelConcernsWithStartRow; use MaatwebsiteExcelConcernsWithHeadingRow; use MaatwebsiteExcelConcernsWithValidation; use MaatwebsiteExcelConcernsSkipsEmptyRows; use IlluminateSupportCollection; use MaatwebsiteExcelConcernsToCollection; use Auth; use AppModelsUser; class ImportedStudentProfile implements ToModel, WithStartRow, WithHeadingRow, WithValidation, SkipsEmptyRows, ToCollection { use Importable; public function model(array $row) { // Define Each Row return new User([ 'name_title_code' => $row['name_title_code'], 'lname' => $row['lname'], 'gender' => $row['gender'], 'citizen_id' => $row['citizen_id'], 'registered_address' => $row['registered_address'], 'mailing_address' => $row['mailing_address], 'is_same_address' => $row['is_same_address'], 'is_current_outside_country' => $row['is_current_outside_country'], 'created_at' => CarbonCarbon::now(), 'created_by' => Auth::user()->id, 'updated_at' => CarbonCarbon::now(), 'updated_by' => Auth::user()->id, ]); } public function startRow():int { // Skip The First Row as Header return 2; } public function rules(): array { return [ 'name_title_code' => ['required', Rule::exists('name_title', 'code')], 'fname' => 'required', 'lname' => 'required', 'gender' => ['required', Rule::in('F', 'M')], 'citizen_id' => ['required', digits:13, Rule::unique('users', 'citizen_id')], 'registered_address' => 'required', 'mailing_address' => [Rule::requiredIf('is_same_address', 0)], 'is_same_address' => ['required', 'boolean'], 'is_current_outside_country' => ['required', 'boolean', Rule::declinedIf('is_same_address', 1)], '*.name_title_code' => ['required', Rule::exists('name_title', 'code')], '*.fname' => 'required', '*.lname' => 'required', '*.gender' => ['required', Rule::in('F', 'M')], '*.citizen_id' => ['required', digits:13, Rule::unique('users', 'citizen_id')], '*.registered_address' => 'required', '*.mailing_address' => [Rule::requiredIf('is_same_address', 0)], '*.is_same_address' => ['required', 'boolean'], '*.is_current_outside_country' => ['required', 'boolean', Rule::declinedIf('is_same_address', 1)], ]; } } </code>
     <?php 

     namespace AppImports;
     use IlluminateValidationRule;

     use MaatwebsiteExcelConcernsToModel;
     use MaatwebsiteExcelConcernsImportable;
     use MaatwebsiteExcelConcernsWithStartRow;
     use MaatwebsiteExcelConcernsWithHeadingRow;
     use MaatwebsiteExcelConcernsWithValidation;
     use MaatwebsiteExcelConcernsSkipsEmptyRows;

     use IlluminateSupportCollection;
     use MaatwebsiteExcelConcernsToCollection;

     use Auth;
     use AppModelsUser;
     
     class ImportedStudentProfile implements ToModel, WithStartRow, WithHeadingRow, WithValidation, SkipsEmptyRows, ToCollection
     {
         use Importable;

         public function model(array $row)
         {
              // Define Each Row
              return new User([
                   'name_title_code' => $row['name_title_code'],
                   'lname' => $row['lname'],
                   'gender' => $row['gender'],
                   'citizen_id' => $row['citizen_id'],
                   'registered_address' => $row['registered_address'],
                   'mailing_address' => $row['mailing_address],
                   'is_same_address' => $row['is_same_address'],
                   'is_current_outside_country' => $row['is_current_outside_country'],
                   'created_at' => CarbonCarbon::now(),
                   'created_by' => Auth::user()->id,
                   'updated_at' => CarbonCarbon::now(),
                   'updated_by' => Auth::user()->id,
              ]);
         }

         public function startRow():int
         {
              // Skip The First Row as Header
              return 2;
         }

         public function rules(): array
         {
               return [
                    'name_title_code' => ['required', Rule::exists('name_title', 'code')],
                    'fname' => 'required',
                    'lname' => 'required',
                    'gender' => ['required', Rule::in('F', 'M')],
                    'citizen_id' => ['required', digits:13, Rule::unique('users', 'citizen_id')],
                    'registered_address' => 'required',
                    'mailing_address' => [Rule::requiredIf('is_same_address', 0)],
                    'is_same_address' => ['required', 'boolean'],
                    'is_current_outside_country' => ['required', 'boolean', Rule::declinedIf('is_same_address', 1)],

                    '*.name_title_code' => ['required', Rule::exists('name_title', 'code')],
                    '*.fname' => 'required',
                    '*.lname' => 'required',
                    '*.gender' => ['required', Rule::in('F', 'M')],
                    '*.citizen_id' => ['required', digits:13, Rule::unique('users', 'citizen_id')],
                    '*.registered_address' => 'required',
                    '*.mailing_address' => [Rule::requiredIf('is_same_address', 0)],
                    '*.is_same_address' => ['required', 'boolean'],
                    '*.is_current_outside_country' => ['required', 'boolean', Rule::declinedIf('is_same_address', 1)],
               ];
         }
     }

The followings are some part of the code in my ExcelController for import function :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public function import(Request $request)
{
// For Basic Validation
// Conditions for Basic Validation
$rules = [
'file' => 'required|mimes:xlsx,xls',
];
// Messages for Basic Errors
$messages = [
'file.required' => 'Please choose the file you want.',
'file.mimes' => 'The file must be with the extension of .xlsx or .xls only.',
];
// Validate Data
$validator = Validator::make($request->all(), $rules, $messages);
// Error Case : Return Error
if ($validator->fails()) {
return redirect()
->back()
->withInput()
->withErrors($validator)
->with('error', 'Sorry!nSomething went wrong!');
}
// Success Case
else {
// Advanced Validation(s)
// NO
// Get File
$file = $request->file('file');
try{
// Process The Excel File
Excel::import(new ImportUser, $file);
return redirect()
->back()
->with('success', 'Successfully Add Data from Excel!');
}
catch(MaatwebsiteExcelValidatorsValidationException $e){
$failures = $e->failures();
return redirect()
->back()
->with('error', 'Something went wrong in your file!')
->with('failures', $failures);
}
}
}
</code>
<code>public function import(Request $request) { // For Basic Validation // Conditions for Basic Validation $rules = [ 'file' => 'required|mimes:xlsx,xls', ]; // Messages for Basic Errors $messages = [ 'file.required' => 'Please choose the file you want.', 'file.mimes' => 'The file must be with the extension of .xlsx or .xls only.', ]; // Validate Data $validator = Validator::make($request->all(), $rules, $messages); // Error Case : Return Error if ($validator->fails()) { return redirect() ->back() ->withInput() ->withErrors($validator) ->with('error', 'Sorry!nSomething went wrong!'); } // Success Case else { // Advanced Validation(s) // NO // Get File $file = $request->file('file'); try{ // Process The Excel File Excel::import(new ImportUser, $file); return redirect() ->back() ->with('success', 'Successfully Add Data from Excel!'); } catch(MaatwebsiteExcelValidatorsValidationException $e){ $failures = $e->failures(); return redirect() ->back() ->with('error', 'Something went wrong in your file!') ->with('failures', $failures); } } } </code>
public function import(Request $request)
{
    // For Basic Validation
    // Conditions for Basic Validation
    $rules = [
        'file' => 'required|mimes:xlsx,xls',
    ];
    
    // Messages for Basic Errors
    $messages = [
        'file.required' => 'Please choose the file you want.',
        'file.mimes' => 'The file must be with the extension of .xlsx or .xls only.',
    ];

    // Validate Data
    $validator = Validator::make($request->all(), $rules, $messages);

    // Error Case : Return Error
    if ($validator->fails()) {

        return redirect()
                    ->back()
                    ->withInput()
                    ->withErrors($validator)
                    ->with('error', 'Sorry!nSomething went wrong!');
    }

    // Success Case  
    else {
        
        // Advanced Validation(s)
        // NO

        // Get File
        $file = $request->file('file');

        try{

            // Process The Excel File
            Excel::import(new ImportUser, $file);

            return  redirect()
                    ->back()
                    ->with('success', 'Successfully Add Data from Excel!');
        } 
        catch(MaatwebsiteExcelValidatorsValidationException $e){

            $failures = $e->failures();

            return  redirect()
                    ->back()
                    ->with('error', 'Something went wrong in your file!')
                    ->with('failures', $failures);
        }
    }
}

I cannot use the specified rules in the ‘ImportUser’ to validate the value of each cell in each row such as Rule::unique(‘table_name’, ‘column_name), Rule::requiredIf(‘field_name’, some_value) and Rule::declinedIf(‘field_name’, some_value). For example, I migrated the database so all the records are gone and tried to insert data with Excel but it keeps telling that the ‘citizen_id’ is not unique while there is no records in the database at all.

It keep failing when I try to insert data and keep telling that there is something wrong with the rules I declared. I don’t know why. If anyone has any ideas about this, please do not hesitate to leave yours here.

Thank you in advanced.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật