Custom Authentication with validation in laravel

Hello everyone, Welcome back to justlaravel.com. In the previous post, we discussed about custom authentication in laravel, here we ‘ll add one more cool feature of this elegant framework, which is validation.

Validation rules

We ‘ll here add some validation rules to login and register forms from the previous post.First let us list out the rules we want.
Validation rules for signup form:

We have three fields in our form – email, username and password, validation rules for them are

  • email valid, unique and it’s a required field
  • username unique, contains only alphanumeric characters, minimum of 4 characters and it’s a required field
  • password minimum of 6 characters, it should match the confirm password field and it’s a required field

these rules are defined as,

$rules = array ( ’email’ => ‘required|unique:users|email’, ‘username’ => ‘required|unique:users|alpha_num|min:4’, ‘password’ => ‘required|min:6|confirmed’ );

                ’email’ => ‘required|unique:users|email’,                 ‘username’ => ‘required|unique:users|alpha_num|min:4’,                 ‘password’ => ‘required|min:6|confirmed’

Validation rules for the signin form:

Actually, we don’t need any rules for the login form, as it only checks the credentials from the database and returns an error if the credentials are not found, that’s enough rather than showing errors like username should be 6 characters, alpha numeric…. However, if we want rules, we can define some rules like the signup rules above.

In this application, we don’t even need ‘required’ rule as we used HTML required attribute in our form.

If the validation fails, we ‘ll redirect to the same form with errors,

if ($validator->fails ()) { return Redirect::back ()->withErrors ( $validator, ‘register’ )->withInput (); }

if ($validator->fails ()) {             return Redirect::back ()->withErrors ( $validator, ‘register’ )->withInput ();

Then it will return to form, there we can display the errors the way we want,

@if (count($errors->register) > 0)

    • @foreach ($errors->register->all() as $error)

{{ $error }}

@endforeach

@endif

@if (count($errors->register) > 0)                  @foreach ($errors->register->all() as $error)

Now when we fill our signup form with errors, it shows the errors – see the screen shots below,

justLaravel – Custom Authentication with validation justLaravel – Custom Authentication with validation

You might also like

More Similar Posts