Search code examples
phplaravellaravel-validation

Showing only one validation message for my array of inputs


I have a form that has 10 inputs fields, I want to check if any of those input fields are empty. If they do are empty or have more than 2 characters I want to display only one error message. With my current code I show an error for each field that is empty. I don't want the user to see 10 error messages. I tried many other methods but doesn't seem to work.

I want the error message to say: 'Predictions can't be empty or have more than 2 characters'

The controller

 public function store(Request $request) {
        $requestData = $request->get('match');
        $this->validate($request, [
            'match.*.homeTeam' => 'required|max:2',
            'match.*.awayTeam' => 'required|max:2'
        ]);
         try {
            collect($requestData)
                ->each(function ($match, $key) {
                    Prediction::create([
                        'user_id'  => auth()->id(),
                        'match_id' => $key,
                        'homeTeam' => $match['homeTeamName'],
                        'awayTeam' => $match['awayTeamName'],
                        'homeScore'=> $match['homeTeam'],
                        'awayScore'=> $match['awayTeam'],
                        'result'   => false
                    ]);
            });
            auth()->user()->participated = true; 
            auth()->user()->addPoint();
            auth()->user()->save();

            return redirect('/predictions')->with('success', 'Weekly prediction created, new predictions can be made every Tuesday!');

         } catch(\Exception $e) {
            return view('error.error');
         }   

    }

My messages.blade.php file

@if(count($errors) > 0)
@foreach($errors->all() as $error)
        <div class="alert alert-red">
            {{$error}}
        </div>
    @endforeach   
@endif

@if(session('success'))
    <div class="alert alert-green">
        {{session('success')}}
    </div>
@endif

@if(session('error'))
    <div class="alert alert-danger">
        {{session('error')}}
    </div>
@endif

The view

@include('inc.messages')
{!! Form::open(['method'=> 'POST', 'action'=>'PredictionController@store']) !!}
@foreach($matches as $match)
  <tr>
      <td> <small style="opacity: 0.5; font-size: 10px;">{{$match->date->formatLocalized('%d %B %Y')}} <small></td>
      <td>{{$match->date->format('H:i')}}</td>
          {{Form::hidden('match[' . $match->match_id . '][homeTeamName]', $match->homeTeam )}}
          {{Form::hidden('match[' . $match->match_id . '][status]', $match->status )}}
      <td>{{$match->homeTeam}}</td>
      <td>{{$match->awayTeam}}</td>
          {{Form::hidden('match[' . $match->match_id . '][awayTeamName]', $match->awayTeam )}}
      <td style="width: 150px !important;"><div>{{Form::number('match[' . $match->match_id . '][homeTeam]' , '', [ 'class' =>'form-control-sm col col-sm-3'])}} <span class="ml-2" style="color: white;">-</span> {{Form::number('match[' . $match->match_id . '][awayTeam]' , '', ['class' =>'form-control-sm col col-sm-3 ml-2'])}} </div></td>                      
 </tr>
@endforeach
{{Form::button('Submit', ['type' =>'submit', 'class' => 'submit-btn float-right mb-3'])}} 
{!! Form::close() !!}

Any tips?


Solution

  • I think you can do something like this:

    @if($errors)
        <div class="alert alert-red">
            {{ $errors->first() }}
        </div>  
    @endif
    

    If there are errors, only show the first one.