5

for a dynamic form in which fields can be added and modified:

in form

<input name="gallery[1][title]">
<input name="gallery[1][text]">
.
.
.
<input name="gallery[n][title]">
<input name="gallery[n][text]">

in controller for validation:

'gallery.*.file' => 'nullable|image',
'gallery.*.title' => 'nullable|string',

in localization file:

I never know how many are going to be in the array.

'gallery.*.text' =>  'text of gallery 1',
'gallery.*.title' =>  'title of gallery 1',

how can I write it?

I want something like this in results:

title of gallery 1

.

.

.

title of gallery n

Maria
  • 185
  • 1
  • 2
  • 12

3 Answers3

1

Here's a hacky way to do this. Unfortunately laravel does not currently support adding general message replacers for specific tokens so here's what you could do:

In controller:

$replacer = function ($message, $attribute) {
    $index = array_get(explode(".",$attribute),1);
    $message = str_replace(":index",$index,$message);
    //You may need to do additional replacements here if there's more tokens
    return $message;
}
$this->getValidationFactory()->replacer("nullable", $replacer);
$this->getValidationFactory()->replacer("string", $replacer);
$this->getValidationFactory()->replacer("image", $replacer);
$v = $this->getValidationFactory()->make($request->all(), $rules);
if ($v->fails()) {
   $this->throwValidationException($request, $v); //Simulate the $this->validate() behaviour
}

You could also add the replacers in the service provider to have them available in all routes, but unfortunately you need to register them for each rule you want them available for.

In localisation file:

'gallery.*.text' =>  'text of gallery :index',
'gallery.*.title' =>  'title of gallery :index',
Sinan Gül
  • 569
  • 7
  • 18
apokryfos
  • 38,771
  • 9
  • 70
  • 114
1

Update in laravel 7

your_language/validation.php

es it/validation.php

'attributes' => [
       'gallery.*.file' => 'Your custom message!!',
    ],
Francesco Taioli
  • 2,687
  • 1
  • 19
  • 34
0

Need to modify the form and controller validation

IN Form

 {!! Form::open(['url' => 'actionURL']) !!}
    {{ csrf_field() }}
      <input name="gallery[]">

    {!! Form::close() !!}

In Controller

  foreach ($request->gallery as $key => $gallery) {        
       $validator = Validator::make(array('gallery => $gallery),
                array('gallery' => 'required'));        
}
Gowthaman D
  • 574
  • 7
  • 19