Validate if only one file is selected in Laravel

1

I want to validate a field type file that is not required, but only if a file has been selected validate the type and size

This is on my controller:

if($request->hasFile('File')){
     $file = $request->file('File');
     $name = date_format($date,'Y-m-d').'_'.explode(' ',$emp->LastName)[0].'_'.explode(' ', $emp->Name)[0].'_'. $file->getClientOriginalName();
     $path = Storage::putFileAs('test_img', $file, $name);
  }else{
     $path = null;
}
    
asked by gmrYaeL 23.11.2018 в 21:25
source

3 answers

1

I propose to create a FormRequest for the respective validations, with the command

// reemplazar Model por el nombre del modelo el cuál validará
php artisan make:request ModelFormRequest  

From this, generate the rules, where the most important would be a if simple within rules (method that generates the command, also for the moment return true in the authorize method)

public function rules()
{ 

 $rules = [
    'uncampo' => 'required',
    'otrocampo' => 'required|min:5',
  ];
  // Si el campo File se selecciono un archivo realizamos las validaciones
  // respectivas como el tamaño y el tipo 
  if ( $this->hasFile('File') )
  {
    $rules['File'] = ['max:2000','mimes:pdf,docx,doc'];
  }
  return $rules;
}
    
answered by 24.11.2018 в 02:09
0

You can add a validation with a Validator in your controller to validate the received file, you can specify what type of file or what size you need.

    $file = $request->file('File');
    $validator = Validator::make(
                        array(
                            'file' => $file,
                        ),
                        array(
                            'file' => 'file|max:5000|mimes:pdf,docx,doc',
                        )
                    );
//Si no pasa la validacion realizas una accion
  if ($validator->fails()) {
       return Redirect::to('miruta');
  }
    
answered by 23.11.2018 в 22:34
0

I think you should simply add the nullable rule to your validation of the FILE field.

 'file' => 'nullable|file|max:5000|mimes:pdf,docx,doc'
    
answered by 23.11.2018 в 22:42