Consent

This site uses third party services that need your consent.

Skip to content
Steven Roland

Laravel's in Validation Rule: Restricting Input to Predefined Values

When developing web applications, it's often necessary to limit user input to a specific set of predefined values. Laravel's in validation rule provides an elegant solution for this requirement. In this blog post, we'll explore the in rule, its usage, and provide real-world examples to illustrate its practical applications.

What is the in Validation Rule?

The in:foo,bar,... validation rule in Laravel checks if the input value is included in a given list of values. This rule is particularly useful for validating fields like dropdown selections, radio buttons, or any input where the user should choose from a predefined set of options.

How to Use the in Rule

Implementing the in rule in Laravel is straightforward. Here are a few ways to apply it:

  1. In controller methods:

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'status' => 'required|in:pending,approved,rejected',
            'priority' => 'required|in:low,medium,high',
        ]);
    
        // Process the validated data
    }
  2. In form request classes:

    class CreateTaskRequest extends FormRequest
    {
        public function rules()
        {
            return [
                'title' => 'required|string|max:255',
                'category' => 'required|in:work,personal,shopping',
            ];
        }
    }
  3. Using the Validator facade:

    $validator = Validator::make($request->all(), [
        'payment_method' => 'required|in:credit_card,paypal,bank_transfer',
    ]);

Real-World Examples

Let's explore some practical examples of using the in rule in different scenarios:

Example 1: User Role Assignment

When assigning a role to a user:

public function assignRole(Request $request, User $user)
{
    $validatedData = $request->validate([
        'role' => 'required|in:admin,editor,viewer',
    ]);

    $user->role = $validatedData['role'];

    $user->save();

    return redirect()->route('users.show', $user)->with('success', 'Role assigned successfully!');
}

In this example, we ensure that the assigned role is one of the predefined options.

Example 2: Product Category Selection

When creating or updating a product:

public function store(Request $request)
{
    $validatedData = $request->validate([
        'name' => 'required|string|max:255',
        'price' => 'required|numeric|min:0',
        'category' => 'required|in:electronics,clothing,books,home,sports',
    ]);

    $product = Product::create($validatedData);

    return redirect()->route('products.show', $product)->with('success', 'Product created successfully!');
}

Here, we validate that the selected category is one of the allowed options.

Example 3: Order Status Update

When updating the status of an order:

public function updateStatus(Request $request, Order $order)
{
    $validatedData = $request->validate([
        'status' => 'required|in:pending,processing,shipped,delivered,cancelled',
    ]);

    $order->status = $validatedData['status'];

    $order->save();

    return redirect()->route('orders.index')->with('success', 'Order status updated successfully!');
}

In this example, we ensure that the new status is one of the predefined order statuses.

Advanced Usage of in

The in rule can be used in more advanced scenarios:

  1. Using an array instead of a comma-separated list:

    $rules = [
        'fruit' => 'required|in:' . implode(',', ['apple', 'banana', 'orange']),
    ];
  2. Using the Rule class for more complex scenarios:

    use Illuminate\Validation\Rule;
    
    $rules = [
        'status' => ['required', Rule::in(['active', 'inactive'])],
    ];
  3. Combining with other rules:

    'priority' => 'required|string|in:low,medium,high|max:6',

Handling Validation Errors

When the in rule fails, Laravel will automatically return a validation error. However, you might want to provide a more specific error message:

$messages = [
    'status.in' => 'The selected status is invalid. Please choose from pending, approved, or rejected.',
    'category.in' => 'The selected category is not valid.',
];

$validator = Validator::make($request->all(), [
    'status' => 'required|in:pending,approved,rejected',
    'category' => 'required|in:work,personal,shopping',
], $messages);

Considerations and Best Practices

  1. Case Sensitivity: The in rule is case-sensitive. Ensure your predefined values match exactly what you expect from the input.

  2. Dynamic Values: If your allowed values are dynamic (e.g., fetched from a database), consider using the Rule class to build the validation rule.

  3. Maintenance: Keep your list of allowed values updated. If you add or remove options, remember to update your validation rules.

  4. User Experience: Ensure that the options you're validating against match the options you're presenting to the user in your UI.

  5. Localization: If you're working on a multi-language application, consider storing your predefined values in language files for easy translation.

Conclusion

The in validation rule in Laravel is a powerful tool for restricting input to a predefined set of values. Whether you're dealing with user roles, product categories, order statuses, or any other scenario requiring selection from a fixed set of options, this rule helps maintain data integrity and improves the overall reliability of your application. By combining the in rule with other validation rules and implementing clear user interfaces, you can create robust forms that effectively validate user input against your application's specific requirements.

More posts

Laravel's url Validation Rule: Ensuring Valid URL Inputs

This post explains Laravel's url validation rule, its usage, and provides real-world examples for user profiles with social media links, adding resource links, and submitting websites for review. It also covers advanced usage, error handling, and best practices for URL validation.

Laravel's email Validation Rule: Ensuring Valid Email Addresses

This post explains Laravel's email validation rule, its usage, and provides real-world examples for user registration, newsletter subscription, and contact form submission. It also covers advanced usage, error handling, and best practices for email validation.

Laravel's not_in Validation Rule: Excluding Specific Values

This post explains Laravel's not_in validation rule, its usage, and provides real-world examples for preventing reserved usernames, excluding generic product categories, and filtering out common weak passwords. It also covers advanced usage, error handling, and best practices.