Search code examples
laravelvalidationmiddleware

validation with middleware for registration form in laravel


I want to make a registration form for users which having input fields like name, email, mobile,..etc such that if user enter email address which is already register by another user then error will be arises "email is already in used" and other input field values remains as it is as client enter before submitting the form.


Solution

  • you can use laravel validation for unique on post of your registration form

    $validator = Validator::make($request->all(), [
         'email'       => 'email|unique:table_name,col_name',
        ],[
         'email.unique' => 'email is already in used',
       ]);
    
    if ($validator->fails()) {
        return redirect()->back()->withInput($request->all())->withErrors($validator);
      }
    

    on your register.blade add this to view error msg:

    @if($errors->any()){{$errors->first()}}@endif
    

    to keep all user-filled values as it is, use laravel's "old" keyword in all of your input fields like example:

    <input type="text" name="email" value="{{ old('email') }}">