DEV Community

Mahmoud Ramadan
Mahmoud Ramadan

Posted on

Simplify Laravel Validation with the Rule Class

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.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.