Laravel custom validaion rules with custom message set.

Shah Md. Iktakhairul Islam
2 min readAug 28, 2022

--

Applying in student login page:

Desire output in frontend

There are some way to do this based on requirements —

  1. Login success when only status is active
This is one way when login success when status is active
$this->validate($request, [
'email' => 'exists:students,email,status,active',
], [
'email.exists' => 'Your account is not activated yet. Please verify email or contact with authority.'
]);

2. When need more to check by database query

Firstly check basic email password validation, then set rules with query, message set, apply validation and return validation message if validation fails.

When need to query for check more column
/**
* General email validation with exists check
*/
$this->validate($request, [
'email' => 'required|email|exists:students,email',
'password' => 'required',
]);

/**
* Custom validation rules, message return and validate
*/
$rules = [
'email' => [
Rule::exists('students', 'email')->where(function ($query) {
return $query->where('status', '!=', 'un_verified')->where('email_verified_at', '!=', '');
}),
],
];
$messages = ['email.exists' => 'Your account is not activated yet. Please verify email or contact with authority.'];
$email = Validator::make($request->all(), $rules, $messages);
if ($email->fails()) {
return redirect()->route('student.student_login')->withErrors($email)->withInput();
}

— Shah Md. Iktakhirul Islam, Software Engineer.

Contact Number: +8801683201359

Email: iktakhairul@gmail.com

GitHub Profile: https://github.com/iktakhairul

--

--