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.