xxxxxxxxxx
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string',
'age' => 'required|integer',
'gender' => 'sometimes|string', // Add 'sometimes' rule for optional field
]);
$validator->after(function ($validator) {
// Set default value for 'gender' field if it is not provided
$validator->mergeDefaults([
'gender' => 'unknown',
]);
});
if ($validator->fails()) {
// Handle validation errors
}
// Validation passed, proceed with other actions
}