1

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?

2
  • can you add your form code also? Commented Nov 10, 2018 at 14:46
  • updated the code Commented Nov 10, 2018 at 15:02

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

validate() method can take a third argument specifying the cusom error message.

To display just one, customized error message for any validation fail.

You can do:

    $this->validate(
         $request, 
         [ 
            'match.*.homeTeam' => 'required|max:2',
            'match.*.awayTeam' => 'required|max:2'
         ],
         ['match.*' => "Predictions can't be empty or have more than 2 characters"]);

Comments

0

You can retrieve the first error message for a given key as follows:

foreach ($errors->first('match.*') as $message) {
    //
}

For more information, check Laravel's documentation on Validation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.