Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show only error message in Laravel Validator

I want only error messages not the field with codes

Controller

 $validator = Validator::make(request()->all(),[
        'txtName' =>'required|max:25',
       ]);

     if($validator->fails()) {
            $errors = $validator->errors();
            return redirect()->back()->with('error', $errors);
        }

View:

@if(session()->has('error'))
{!! \Session::get('error') !!}
@endif

Return:

{"txtName":["The txt name may not be greater than 25 characters."]}

What I need:

name may not be greater than 25 characters

like image 346
Anonymous Girl Avatar asked Dec 07 '25 07:12

Anonymous Girl


2 Answers

First instead of with use withErrors

 if($validator->fails()) {
            $errors = $validator->errors();
            return redirect()->back()->withErrors($errors);
        }

and in view

@if($errors->any())
     <div class="alert alert-danger">
          <ul class="list-unstyled">
                 @foreach ($errors->all() as $error)
                       <li>{{ $error }}</li>
                 @endforeach
          </ul>
      </div>
 @endif
like image 59
John Lobo Avatar answered Dec 08 '25 22:12

John Lobo


Use @foreach.

@if(session()->has('error'))

   @foreach($errors->all() as $error as $error)
      <p>{{ $error }}</p>
   @endforeach

@endif
like image 28
Adrian Zavis Avatar answered Dec 08 '25 21:12

Adrian Zavis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!