1
votes

I am using laravel 5 to built a user logging page and I have used validate() function to validate the email,password and first_name fields.

User Controller

class UserController extends Controller{

    public function getDashBoard(){
        return view('dashboard');
    }
    public function postSignUp(Request $request){

        $this->validate($request,[
            'email'=>'required|email|unique:users',
            'first_name'=>'required|max:120',
            'password'=>'required:min:4'
        ]);

        $user=new User();
        $user->email=$request['email'];;
        $user->first_name=$request['first_name'];
        $user->password=bcrypt($request['password']);;
        $user->save();
        Auth::login($user);
        return redirect()->route('dashboard');  
    }
 }

This function work correctly and when data is invalid it returns to the previous page. I have used following code to show error messages in welcome.blade.php file.

    @if(count($errors)>0)
        <p>Error occurred</p>            
    @endif

In case of validation error, it returns back to the welcome page bt the above error message is not displayed (count($errors) is always equal to 0 , when i check). What is the problem here?

routes.php

Route::group(['middleware'=>['web']],function(){

    Route::get('/', function () {
        return view('welcome');
    });

    Route::post('/signup',['uses'=>'UserController@postSignUp','as'=>'signup']);

    Route::post('/signin',['uses'=>'UserController@postSignIn','as'=>'signin']);

    Route::get('/dashboard',[
        'uses'=>'UserController@getDashboard','as'=>'dashboard'
    ]);
});
1
Have you tried @if($errors->has()) instead of counting it? - henriale
it also doesn't work - chamathabeysinghe
what's the type of $errors? it should be an instance of ViewErrorBag - henriale

1 Answers

0
votes

Try this :

$validator = Validator::make($request->all(), [
        'email'=>'required|email|unique:users',
        'first_name'=>'required|max:120',
        'password'=>'required:min:4'
    ]);

    if ($validator->fails()) {
        return redirect('/signin')
                    ->withErrors($validator)
                    ->withInput();
    }

    $user=new User();
    $user->email=$request['email'];;
    $user->first_name=$request['first_name'];
    $user->password=bcrypt($request['password']);;
    $user->save();
    Auth::login($user);
    return redirect()->route('dashboard');  

Let me know if it helps you