When working with validated data, we can use validated()
to retrieve an array of the validated request data.
We can use safe()
instead to get a ValidatedInput
instance, which has a lot of helpers like only()
, except()
, and merge()
. Additionally, it provides other methods like whenHas()
and whenFilled()
for conditional logic.
// Retrieve all validated data
$validated = $requestOrValidator->validated();
// Use safe() to access additional helpers
$validated = $requestOrValidator->safe();
// Extract specific fields
$onlyNameAndEmail = $validated->only(['name', 'email']);
// Exclude specific fields
$withoutPassword = $validated->except(['password']);
// Add new fields to the validated data
$mergedData = $validated->merge(['role' => 'member']);
// Conditional handling of specific fields
$validated->whenHas('name', function ($value) {
// Handle email if it exists
});
$validated->whenFilled('name', function ($value) {
// Handle name if itβs not empty
});