Добавление имени файла, загруженного в сообщение проверки Laravel

У меня есть массив загружаемых файлов. В языковой файл validation.php я добавил пользовательские сообщения об ошибках:

'custom' => [
    'images.*'      => [
            'dimensions' => 'Image ":file" must have a min-height of :min_height pixels and a min-width of :min_width pixels.',
            'image'      => 'You can only upload images to your gallery. The file ":file" was not an image.',
            'mimes'      => 'Your image ":file" was an invalid type. Images can only be of the following types: :mimes',
            'max'        => 'Max file size for each image is :max MB. Your image ":file" is too large.'
        ]
]

Поскольку загружается несколько файлов, я хотел бы указать, к какому файлу относится сообщение об ошибке, когда я отображаю ошибки проверки.

@if($errors->has('images.*'))
    @foreach ($errors->get('images.*') as $message)
        <div class="help-block has-error">{{ head($message) }}</div>
    @endforeach
@endif

Однако :file не заполняется автоматически в сообщении, и я не знаю, как его получить.

Как мне это сделать? Есть ли другой заполнитель или метод, который я могу использовать?


person eComEvo    schedule 12.07.2017    source источник
comment
Я думаю, что для этой цели лучше написать собственный класс проверки изображений.   -  person ako    schedule 13.07.2017
comment
@ako, если есть стандартный простой способ просто вставить имя файла в сообщение проверки, я бы предпочел сначала пойти по этому пути.   -  person eComEvo    schedule 13.07.2017


Ответы (1)


У меня та же проблема, я пытаюсь получить имена файлов в массиве и поместить их в пользовательское сообщение об ошибке в зависимости от типа проверки в моем примере, я получу имя файла в зависимости от типа изображения (jpeg, png, jpg , SVG, BMP)

В файле контроллера:

//...
public function store(Request $request)
    {
$rules = [        'imagefile' => 'required',
                  'imagefile.*' => 'image|mimes:jpeg,png,jpg,svg,bmp', // working on filse size custom message 
                 ];

       

        // To get name of non image file and display in it in error message 
        if($request->hasfile('imagefile')){
           
           $names = array(); // array for all names of files
          foreach($request->Bank_Logo as $file){
            

            // check file extension
            if($file->getClientOriginalExtension() != 'jpeg' &&
               $file->getClientOriginalExtension() != 'png' && 
               $file->getClientOriginalExtension() != 'jpg' &&
               $file->getClientOriginalExtension() != 'svg' &&
               $file->getClientOriginalExtension() != 'bmp'){

               $name= $file->getClientOriginalName (); // get file name 
               $names[] = $name; // set name of file to array 
              
            }
           
          }
        

          // check names array if it empty or not
          if(!empty($names)){
  
            /* but all names in custom error,message 
             * implode funaction to convert array to string 
             */
            $messages = [
                'imagefile.*image' => 'The ' . implode(" and ",$names) . ' not an image file.',
                'imagefile.*mimes' =>  'The ' . implode(" and ",$names) . ' must be a file of type: jpeg, png, jpg, svg, bmp.'
                  ];
          }         
        }              


               if(!empty($messages)){
                  $result = Validator::make($request->all(), $rules, $messages); // with custom message 
                   //dd($result);
               }
               else{ 
                   $result = Validator::make($request->all(), $rules); // without custom message
                    //dd('empty');
               }
        

        if($result->fails())
        {
            return back()->withErrors($result)->withInput($request->all());   
        }
       

        dd($request->all());

      //...
} 

В файле balde

//...
<form>

label class="form-control-label mt-3">{{ __('imagefileLogo') }}</label>
                            <div class="file-loading">
                                <input id="imagefile" name="imagefile[]" type="file" multiple>
                            </div>

                            @if ($errors->has('imagefile'))
                            <span class="invalid-feedback" style="display: block;" role="alert">
                                <strong>{{ $errors->first('imagefile') }}</strong>
                            </span>
                            @endif

                            @if ($errors->has('imagefile.*')) <!--in case if we have multiple file-->
                            <span class="invalid-feedback" style="display: block;" role="alert">
                                <strong>{{ $errors->first('imagefile.*') }}</strong>
                            </span> 
                            @endif    

<form>  
//...

То же самое вы можете сделать с размером файла.

Кроме того, я использую [этот плагин] для ввода загружаемого файла [этот плагин]: https://plugins.krajee.com/file-input#top

Ларавель версии 5.8

Я надеюсь, что это было полезно для вас. если у кого-то есть лучший способ, пожалуйста, обсудите.

person SWAT 10101    schedule 05.06.2020
comment
Проверьте также это - person SWAT 10101; 09.06.2020