Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validator and excel files error

I have an input field who allaow peoples to upload files. I want that they can upload, word files like doc, and files like csv,xlsx.

When i try with a .doc no problem at all but when i try with an excel files, the validator fail and say that not the good extension.

Here you can see my code, the two lines of comments was an other solution i have try , and it don't work too :(.

Any help is welcome.

public function postFile(Request $request)
{ //Règle de validation avec les type de fichiers acceptés

 if(isset($request->file)){
//dd($request);
   $validator=Validator::make($request->all(),[
     'file'=>'required|max:50000|mimes:xlsx,doc,docx,ppt,pptx,ods,odt,odp,application/csv,application/excel,
      application/vnd.ms-excel, application/vnd.msexcel,
      text/csv, text/anytext, text/plain, text/x-c,
      text/comma-separated-values,
      inode/x-empty,
      application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  /*  'extension'  => strtolower($request->file->getClientOriginalExtension()),
     'extension'=>'required|in:doc,csv,xlsx,xls,docx,ppt,odt,ods,odp'*/
   ]);
  if ($validator->fails()) {
     return back()
                ->withErrors($validator);
   }
like image 971
Exarkun Avatar asked Feb 07 '17 12:02

Exarkun


People also ask

How do I translate validation errors in Laravel?

Laravel's built-in validation rules each has an error message that is located in your application's lang/en/validation.php file. Within this file, you will find a translation entry for each validation rule. You are free to change or modify these messages based on the needs of your application.

How to do row validation in Laravel without using tomodel?

If you are not using the ToModel concern, you can very easily do row validation by just using the Laravel validator. Sometimes data may not pass validation directly, but still be valid.

How do I get all validation errors in Excel?

You can try-catch the ValidationException. On this exception you can get all failures. Each failure is an instance of Maatwebsite\Excel\Validators\Failure. The Failure holds information about which row, which column and what the validation errors are for that cell.

How to install Laravel maatwebsite/excel in Linux?

Here, we need install Laravel application using bellow command, So open your terminal OR command prompt and run bellow command: In this step we need to install maatwebsite/excel package via the Composer package manager, so one your terminal and fire bellow command: Now open config/app.php file and add service provider and aliase. .... ....


3 Answers

Ok, my fault. I had tried another solution, found on this website and it worked. Thanks for help Odin. It was my first question on this website. I am gonna see if I can help someone now. I post code for solution for someone in need :).

$validator = Validator::make(
  [
      'file'      => $request->file,
      'extension' => strtolower($request->file->getClientOriginalExtension()),
  ],
  [
      'file'          => 'required',
      'extension'      => 'required|in:doc,csv,xlsx,xls,docx,ppt,odt,ods,odp',
  ]
);
like image 109
Exarkun Avatar answered Oct 09 '22 08:10

Exarkun


Use "mimes" when you want to write an extentions (xlsx,doc,docx). In case when use mime-type like application/vnd.ms-excel you must use validation rule mimetype

More mime types: more mime-types

$validator=Validator::make($request->all(),[
 //use this
    'file'=>'required|max:50000|mimes:xlsx,doc,docx,ppt,pptx,ods,odt,odp'
 //or this
    'file'=>'required|max:50000|mimetypes:application/csv,application/excel,
        application/vnd.ms-excel, application/vnd.msexcel,
        text/csv, text/anytext, text/plain, text/x-c,
        text/comma-separated-values,
        inode/x-empty,
        application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
]);
like image 10
Odin Thunder Avatar answered Oct 09 '22 07:10

Odin Thunder


Here's how I did it in Laravel 6 by checking the file extension.

Create a new validation rule:

php artisan make:rule ExcelRule

Here is the ExcelRule, which checks the file extension:

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Http\UploadedFile;

class ExcelRule implements Rule
{
    private $file;

    public function __construct(UploadedFile $file)
    {
        $this->file = $file;
    }

    public function passes($attribute, $value)
    {
        $extension = strtolower($this->file->getClientOriginalExtension());

        return in_array($extension, ['csv', 'xls', 'xlsx']);
    }

    public function message()
    {
        return 'The excel file must be a file of type: csv, xls, xlsx.';
    }
}

As you can see, I'm checking for csv, xls, or xlsx here. You can add any additional extensions you desire.

Using it in a controller:

public function uploadExcelFile(Request $request)
{
    $request->validate([
        'excel_file' => ['required', new ExcelRule($request->file('excel_file'))],
    ]);

    $model->update([
        'excel_file' => $request->file('excel_file')->store('excel_files'),
    ]);

    return redirect()->route('my_route_name')->with('Excel file uploaded!');
}
like image 6
stardust4891 Avatar answered Oct 09 '22 07:10

stardust4891