najmulcse's avatar

Error messages are not shown after validation

I want to show error messages after validating of a form . But its not showing the error message when it redirected into previous page . Important point is noted that form validation is working but error message is not shown .

I'm printed for errors checking by {{print_r($errors)}} in my form and its show the following message :Illuminate\Support\ViewErrorBag Object ( [bags:protected] => Array ( ) ) 1

It is assure that the validation is worked properly . When i submitted my form without any values it's not going to other page , it redirected to current page .

#Here i posted my form in a controller method

public function storeLecture(Request $request ){

      $rules=[
          'lecture_title'  => 'required ',
          'body'           => 'required',
          'file'           => 'required'
           ];
     $gid=$request->gid;
     $v= Validator::make($request->all(),$rules);
     //$this->validate($request,$rules);
   
     if($v->fails())
            {
             return dd($v);
             //return redirect()->back()->withErrors($v)
                          
                          ->withInput();
            }
      else {
             return  "Ok";
            }
     
     $file= $request->file('file');
     $user_id = Auth::user()->id;
     $post=Post::create([
      'group_id'  => $gid ,
      'user_id'   => $user_id , 
      'title'     => $request->lecture_title ,
      'body'      => $request->body,
      'type'      => 'L'
                      ]);

     if(!empty($file))
     {
        $content=time().$file->getClientOriginalName();
        $post_id=$post->id;
        $file_store=Content::create(['post_id' => $post_id ,'content' =>$content ]);
        $file->move('postfiles',$file_store->id);
     }


      return redirect()->route('allLectures',$gid);  
      

    }

#my form blade file

<form action="{{route('storeLecture')}}" method="POST" enctype="multipart/form-data">
                                      {{ csrf_field() }}                                                             
                                @foreach($errors as $error)
                                      <li>{{$error}}</li>
                                @endforeach 
                                            <input type="hidden" name="gid" value="{{$group->id}}" >
                                      <div class="form-group ">     
                                           <label class="control-label">Lecture Title</label>
                                           <input type="text" name="lecture_title" class="form-control" placeholder="Lecture Title" value="{{old('lecture_title')}}">  
                                     </div>
                                     <div class="form-group">
                                            <label class="control-label">Body</label>
                                            <textarea class="form-control" name="body" rows="5" placeholder="Write here...">{{ old('body') }}</textarea>
                                      </div>
                                     <div class="form-group">
                                           <label class="control-label">File</label>
                                             <input type="file" name="file" class="form-control" accept=".doc,.ppt,.pdf,.jpeg,.png,.jpg," value="{{ old('file') }}">     
                                     </div>
                                     <div class="form-group">

                                          <button type="submit" class="btn btn-sm btn-success pull-right">Upload lecture</button>   
                                    </div>
                           </form> 


#routes are

Route::get('group/{gid}/allLectures',['as' => 'allLectures' , 'uses' => 'PostController@allLectures']);
    Route::get('group/{gid}/createLecture',['as' => 'createLecture','uses' => 'PostController@createLecture']);
    Route::post('group/Lecture/store',['as' => 'storeLecture','uses' => 'PostController@storeLecture']);


When i check the return value for showing all validation by dd($v) its catch the validation but when it redirected to return redirect()->back()->withErrors($v) ->withInput();

no error messages are showing in my form .

Please help me to solve this problem .

0 likes
23 replies
nick.a's avatar

$errors is an object and an instance of Illuminate\Support\MessageBag. If you want to iterate it the way you are trying to, you need to use the all() method on the $errors object like this:


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

nick.a's avatar

Is there a reason you aren't using the validate method? All Laravel controllers use the ValidatesRequests trait which allows you to do something like this:

public function storeLecture(Request $request)
{
    $this->validate($request, [
        'lecture_title'  => 'required',
        'body'           => 'required',
        'file'           => 'required'
    ]);

    // Lecture is valid and can be stored.
}

If the validate function fails, it will automatically redirects back with the proper errors.

najmulcse's avatar

@Nicholas All possibles function already tested but no results found for showing errors .

Snapey's avatar

Do you have working session storage?

Are users logged in correctly and maintained from page to page?

sujancse's avatar

I need you to try everything from start.

Please try first dd($request->all()); if there is value in request then try

$this->validate($request, [
         'lecture_title'  => 'required ',
         'body'           => 'required',
         'file'           => 'required'
]);

And make sure you are getting the file

Then try to make some error in validation to if it actually get called or not.

If everything goes well you will definitely get the errors as $errors in the view page.

Try $errors->all() it will give you all errors.

DvdEnde's avatar

Its an old message but this worked for me:

 Session::flash('error', $validator->Message);
munazzil's avatar

Have you used this in your header.

use Illuminate\Validation\Validator; 

and also add this in your blade.php

@if ($message = Session::get('error'))
    <div class="alert alert-success">
        <p>{{ $message }}</p>
    </div>
 @endif
cetorres's avatar

@najmulcse did you find a solution for this problem? I'm also having the same problem with Laravel version 5.7. Thank you.

1 like
Behinder's avatar

3 months later and still no solution to the problem. 5.7 sucks..:/

GertjanRoke's avatar

@najmulcse do you have a ad-blocker installed on your browser? I had a same problem and the ad-blocker reloaded my page really fast and because of that the error messages were gone.. atleast take a look at your network tab and Preserve log on

nabilelboudali's avatar

I resolved issue with laravel 5.2.*

As soon as I moved \Illuminate\Session\Middleware\StartSession::class and \Illuminate\View\Middleware\ShareErrorsFromSession::class from web $middlewareGroups to $middleware in app\Http\Kernel.php everything started working as expected.

alaminjwel's avatar

In my case the issue was caused by \Illuminate\Session\Middleware\StartSession::class added in app/Http/Kernel.php in order to initiate session in constructor level. Removing that from kernel fixed my issue.

1 like
hassam's avatar

If you got errors like below. Means validation errors are not properly translated.

validation.required
validation.min.required

Instead of
The title field is required
The title field must have minimum 3 charters

Solution: lang folder it not exists in resources\.

Just copy full lang folder or copy only \lang\en\validation.php file and create new folder inside resources like resources\lang\en\ and paste validation.php file there.

mohit89.verma@gmail.com's avatar

Hi, In Laravel 10, I faced the same problem. After debugging i found the following solution.

In App/Http/Kernel.php file Please make sure that file,

\Illuminate\Session\Middleware\StartSession::class

call only once either in protected $middleware or protected $middlewareGroups (Web)

3 likes
DhPandya's avatar

The StartSession::class middleware is the default on the web. there is no need to specify it. You can always retrieve all the messages of the validator using errors().

$validator->errors();
unrealtone's avatar

I had the same issue in Laravel 10, i solved it by moving my route from api to web. From what i know api routes do not work well with sessions and since $errors works with session it would make sense to use web routes.

Snapey's avatar

@unrealtone api should be sending a json response and the framework will include the errors in the response

Please or to participate in this conversation.