SIMPLIFY LARAVEL VALIDATION WITH THE RULE CLASS

Jun 07, 2025 Copy Link

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.
 */
public function rules(): array
{
    return [
        // 'password' => Rule::when(
        //     auth()->user() instanceof User,
        //     'required|string|max:30'
        // ),
        'password' => Rule::when(
            auth()->user() instanceof User,
            ['required', 'string', 'max:30']
        ),
    ];
}

 

You’ll find more insights in the documentation.

Share via

Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.

Newly published

  • How to Enable Relationship Autoloading in Versions Before v12.8

    How to Enable Relationship Autoloading in Versions Before v12.8

    PREMIUM

  • Get your environment ready to welcome Laravel v12

    Get your environment ready to welcome Laravel v12

    PREMIUM

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using TCPDF

    FREE