When developing web applications, there are scenarios where you need to ensure that user input does not match certain predefined values. Laravel's not_in
validation rule provides an elegant solution for this requirement. In this blog post, we'll explore the not_in
rule, its usage, and provide real-world examples to illustrate its practical applications.
What is the not_in
Validation Rule?
The not_in:foo,bar,...
validation rule in Laravel checks if the input value is not included in a given list of values. This rule is particularly useful for excluding specific options, preventing the use of reserved words, or ensuring uniqueness against a predefined set.
## How to Use the not_in
Rule
Implementing the not_in
rule in Laravel is straightforward. Here are a few ways to apply it:
In controller methods:
public function store(Request $request) { $validatedData = $request->validate([ 'username' => 'required|string|not_in:admin,moderator,superuser', 'email_domain' => 'required|string|not_in:example.com,test.com', ]); // Process the validated data }
In form request classes:
class CreateUserRequest extends FormRequest { public function rules() { return [ 'name' => 'required|string|max:255', 'password' => 'required|string|min:8|not_in:password,123456,qwerty', ]; } }
Using the Validator facade:
$validator = Validator::make($request->all(), [ 'category' => 'required|string|not_in:uncategorized,misc,other', ]);
Real-World Examples
Let's explore some practical examples of using the not_in
rule in different scenarios:
Example 1: Preventing Reserved Usernames
When registering a new user, you might want to prevent certain reserved usernames:
public function register(Request $request)
{
$validatedData = $request->validate([
'username' => 'required|string|max:255|unique:users|not_in:admin,root,system,support',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8|confirmed',
]);
$user = User::create($validatedData);
Auth::login($user);
return redirect()->route('dashboard')->with('success', 'Registration successful!');
}
In this example, we ensure that the chosen username is not one of the reserved system names.
Example 2: Excluding Specific Product Categories
When creating a product, you might want to exclude certain general categories:
public function store(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'price' => 'required|numeric|min:0',
'category' => 'required|string|not_in:general,misc,other',
]);
$product = Product::create($validatedData);
return redirect()->route('products.show', $product)->with('success', 'Product created successfully!');
}
Here, we validate that the selected category is not one of the overly generic options.
Example 3: Filtering Out Common Weak Passwords
When a user is changing their password, you might want to prevent common weak passwords:
public function updatePassword(Request $request)
{
$validatedData = $request->validate([
'current_password' => 'required|current_password',
'new_password' => [
'required',
'string',
'min:8',
'confirmed',
'not_in:password,12345678,qwertyuiop',
Password::defaults(),
],
]);
$request->user()->update([
'password' => Hash::make($validatedData['new_password']),
]);
return back()->with('success', 'Password updated successfully!');
}
In this example, we ensure that the new password is not one of the commonly used weak passwords.
Advanced Usage of not_in
The not_in
rule can be used in more advanced scenarios:
Using an array instead of a comma-separated list:
$forbiddenWords = ['spam', 'scam', 'free']; $rules = [ 'title' => 'required|string|not_in:' . implode(',', $forbiddenWords), ];
Using the Rule class for more complex scenarios:
use Illuminate\Validation\Rule; $rules = [ 'status' => ['required', Rule::notIn(['deleted', 'banned'])], ];
Combining with other rules:
'domain' => 'required|string|not_in:example.com,test.com|unique:websites,domain',
Handling Validation Errors
When the not_in
rule fails, Laravel will automatically return a validation error. However, you might want to provide a more specific error message:
$messages = [
'username.not_in' => 'This username is reserved and cannot be used.',
'category.not_in' => 'Please select a more specific category.',
];
$validator = Validator::make($request->all(), [
'username' => 'required|string|not_in:admin,root,system',
'category' => 'required|string|not_in:general,misc,other',
], $messages);
Considerations and Best Practices
Case Sensitivity: The
not_in
rule is case-sensitive. Ensure your excluded values match exactly what you want to prevent.Dynamic Values: If your excluded values are dynamic (e.g., fetched from a database), consider using the Rule class to build the validation rule.
Maintenance: Keep your list of excluded values updated. Regularly review and update your validation rules as needed.
User Experience: Provide clear feedback to users when they input a value that's not allowed.
Security: While
not_in
is useful, don't rely solely on it for security-critical validations. Combine it with other security measures.
Conclusion
The not_in
validation rule in Laravel is a powerful tool for excluding specific values from user input. Whether you're preventing the use of reserved names, filtering out generic categories, or enhancing password security, this rule helps maintain data integrity and improves the overall quality of user-submitted data in your application. By combining the not_in
rule with other validation rules and implementing clear user feedback, you can create robust forms that effectively guide users towards providing appropriate and secure input.