Laravel
Laravel validation

Laravel validation

Are you trying to validate most of the form request directly from Validator? Well, I do have a solution for that which will make you easy on validation instead of validating stuff directly from your database using lots of queries.

$validator = Validator::make(
            $request->all(),
            [
                'full_name' => 'required',
                'email' => 'required|string|unique:users,email',
                'username' => 'required|string|unique:users,username',
                'mobile' => 'required|string|unique:users,mobile',
                'password' => 'min:6|nullable|required_with:password_confirmation|same:password_confirmation',
                'password_confirmation' => 'min:6|nullable'
            ],
            [
                'full_name.required' => 'Full name is required.',
                'email.required' => 'Email is required.',
                'username.required' => 'User is required.',
                'mobile.required' => 'Mobile is required.'
            ]
        );

What

Hehe, don’t worry, I am going to explain.

  • required
    • It means compulsory
  • string
    • Should be string
  • unique:users,email
    • unique:table,column,id_column_value is the structure you should follow.
      • Example: unique:users,email,' . $id,
      • If you ignore $id, you should enter unique email address field.
      • Else it will ignore unique email address validation for user with id = $id.
    • unique:users,email,'.$user->id.',user_id
      • Use this, if id is not your primary column.
  • min:6
    • Minimum string should be at least of 6.
    • Specific any number as per your need.
  • nullable
    • If set nullable, validation will ignore, if value is null.
    • Else the validation will start working on other validation rules.
    • While validating password, you can provide nullable to passwords, as when users try to update profile section, they might not update password and the fields might also be empty. So, setting nullable will help validator ignore it, if user hasn’t provided password to change.
  • required_with:password_confirmation|same:password_confirmation
    • Assuming the name of your again_password is password_confirmation.
    • This validation helps you to make sure the password and password_confirmation fields are same.

There are other many validation rules too. You can check on Laravel Official Page.

I hope it was helpful. Let me know if you need any help.

Thank you.

Tags :

Leave a Reply