Simplify Laravel Validation with the Rule Class
Mahmoud Ramadan

Mahmoud Ramadan @mmramadan496

About: Computer Science Geek 🧐 || Software Engineer 👨‍💻 || Digging Code Creator 🚀

Location:
Mansoura, Dakahlia, Egypt
Joined:
Jan 15, 2024

Simplify Laravel Validation with the Rule Class

Publish Date: Jun 8 '25
1 1

I previously shared a tip on how to validate attributes conditionally. However, I didn't fully explore the Rule validation class, which provides a convenient when method to handle such cases elegantly. Let’s revisit the example from that tip and see how we can improve it:

use App\Models\User;
use Illuminate\Validation\Rule;

/**
 * Get the validation rules that apply to the request.
 *
 * @return array<string, mixed>
 */
function rules()
{
    return [
        // 'password' => Rule::when(auth()->user() instanceof User, 'required|string|max:30'),
        'password' => Rule::when(auth()->user() instanceof User, ['required', 'string', 'max:30']),
    ];
}
Enter fullscreen mode Exit fullscreen mode

You’ll find more insights in the documentation.

Comments 1 total

Add comment