HTTP Request
The Request class provides an object-oriented interface for interacting with HTTP requests, including input data, headers, files, and server information.
Accessing The Request
Get the current request instance through dependency injection or helper functions:
use Spark\Http\Request;
// Dependency injection in controller
public function store(Request $request) {
// Use request object
$inputs = $request->input(['name', 'email']);
}
// Using helper functions
$request = request(); // Get full request object
$name = request('name', 'default'); // Get specific input
$inputs = request(['name', 'email']); // Get multiple inputs
Request Data
Retrieving Input
// Get query parameter
$id = $request->query('id');
// Get POST parameter
$name = $request->post('name');
// Get all input
$all = $request->all();
// Get filtered attributes
$filtered = $request->all(['name', 'email']);
Checking For Input
if ($request->has('page')) {
// Input exists
}
if ($request->hasAny(['email', 'username'])) {
// At least one exists
}
if ($request->hasAll(['email', 'password'])) {
// All exist
}
Security Note: Always validate and sanitize user input to prevent security
vulnerabilities.
Basic Validation
// Validate with automatic error handling
$input = $request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => 'required|email',
'password' => 'required|min:8'
]);
Manual Validation
try {
$input = validator([
'name' => 'required|string',
'email' => 'required|email'
]);
// Access sanitized data
$email = $input->email('email');
$name = $input->text('name');
} catch (Exception $e) {
// Handle validation error
}
Request Information
// Get request method
$method = $request->getMethod();
// Get request path
$path = $request->getPath();
// Get client IP
$ip = $request->ip();
// Check if AJAX request
if ($request->isAjax()) { ... }
// Check if expects JSON
if ($request->expectsJson()) { ... }
Request Headers
// Get header
$header = $request->header('X-Custom-Header');
// Check content type
if ($request->accept('application/json')) {
// Client accepts JSON
}
Route Parameters
// For route '/user/{id}'
$id = $request->getRouteParam('id');
// Check if parameter exists
if ($request->hasRouteParam('id')) { ... }
Modifying Requests
// Set query parameter
$request->setQueryParam('page', 2);
// Set POST parameter
$request->setPostParam('status', 'active');
// Merge parameters
$request->mergePostParams(['role' => 'admin']);
Note: Request modifications only affect the current instance and won't change
actual superglobals.
Error Handling
Access validation errors and old input:
// Check for errors
if ($request->errors('email')) {
// Field has errors
}
// Get all errors (Error Object)
$errors = $request->errors();
if ($errors->any()) {
foreach($errors->all() as $error) {
echo $error; // Display each error
}
}
if ($errors->has('email')) {
echo $errors->first('email'); // Display the first error for the email field
}
// Get old input
$oldValue = $request->old('email');
Magic Properties
Access request data through dynamic properties:
// Equivalent to $request->query('id') or $request->post('id')
$id = $request->id;
// Check existence
isset($request->name);
// Set values (only affects current instance)
$request->page = 2;
Array Access
The Request class implements ArrayAccess for convenient access:
// Get value
$name = $request['name'];
// Set value
$request['page'] = 2;
// Check existence
isset($request['email']);
// Unset value
unset($request['temp']);
Input Validator
The InputValidator class provides comprehensive validation rules for ensuring data integrity and correctness.
Important: Validation should be performed before sanitization to catch invalid
data
early.
Basic Usage
// Create validator instance
$validator = new InputValidator();
// Define validation rules
$rules = [
'name' => 'required|string|min:3|max:255',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:8|confirmed'
];
// Validate input
if ($validator->validate($rules, $request->all())) {
// Data is valid
$cleanData = $validator->validated();
} else {
// Handle errors
$errors = $validator->getErrors();
}
Validation Rules
Rule | Description | Example |
---|---|---|
required |
Field must be present and not empty | 'name' => 'required' |
email |
Valid email format | 'email' => 'email' |
url |
Valid URL format | 'website' => 'url' |
numeric |
Numeric value | 'age' => 'numeric' |
integer |
Integer value | 'count' => 'integer' |
float |
Floating-point number | 'price' => 'float' |
string |
String value | 'name' => 'string' |
boolean |
Boolean value | 'active' => 'boolean' |
array |
Array value | 'tags' => 'array' |
min |
Minimum length/value | 'password' => 'min:8' |
max |
Maximum length/value | 'title' => 'max:100' |
between |
Value between range | 'age' => 'between:18,65' |
in |
Value in given list | 'status' => 'in:active,pending,blocked' |
not_in |
Value not in given list | 'role' => 'not_in:admin,superadmin' |
regex |
Matches regex pattern | 'zip' => 'regex:/^\d{5}(-\d{4})?$/' |
unique |
Unique value in database | 'email' => 'unique:users,email' |
exists |
Value exists in database | 'user_id' => 'exists:users,id' |
confirmed |
Field matches confirmation field | 'password' => 'confirmed' |
date |
Valid date | 'birthday' => 'date' |
date_format |
Date matches format | 'created_at' => 'date_format:Y-m-d' |
before |
Date is before given date | 'start_date' => 'before:end_date' |
after |
Date is after given date | 'end_date' => 'after:start_date' |
alpha |
Alphabetic characters only | 'first_name' => 'alpha' |
alpha_num |
Alphanumeric characters | 'username' => 'alpha_num' |
alpha_dash |
Alphanumeric with dashes/underscores | 'slug' => 'alpha_dash' |
file |
Valid file upload | 'avatar' => 'file' |
image |
Valid image file | 'photo' => 'image' |
mimes |
File has allowed MIME type | 'document' => 'mimes:pdf,docx' |
password |
Meets password requirements | 'password' => 'password:8,uppercase,numbers' |
Error Handling
// Get all errors
$errors = $validator->getErrors();
// Get first error
$firstError = $validator->getFirstError();
// Custom error messages
InputValidator::setErrorMessages([
'required' => 'The %s field is mandatory',
'email' => [
'default' => 'Invalid email format',
'contact_email' => 'Please provide a valid contact email'
]
]);
// Set a Single Error Message
InputValidator::setErrorMessage('unique', [
'email' => 'This email is already registered',
'username' => 'This username is already taken',
'default' => 'The %s field is already exists'
]);
Advanced Features
Conditional Validation
// Only validate if other field exists
$rules = [
'payment_method' => 'required|in:credit_card,paypal',
'credit_card_number' => 'required_if:payment_method,credit_card'
];
Note: The validator automatically handles different input types (strings,
numbers,
arrays, files) appropriately for each rule.
File Uploads
// Get uploaded file
$file = $request->file('avatar');
// Check if file exists
if ($request->hasFile('avatar')) {
// Process file
$name = $file['name'];
$size = $file['size'];
$tmp = $file['tmp_name'];
}
Input Sanitizer
The InputSanitizer class provides robust data cleaning and sanitization methods to ensure safe handling of user input.
Security Note: Always sanitize user input before processing or storing it to
prevent security vulnerabilities.
Basic Usage
// Create from request input
$input = $request->input(['name', 'email']);
// Or create directly
$sanitizer = new InputSanitizer([
'name' => 'John ',
'email' => 'john@example.com'
]);
// Get sanitized values
$name = $sanitizer->text('name'); // "John Doe"
$email = $sanitizer->email('email'); // "john@example.com"
Sanitization Methods
Method | Description | Example |
---|---|---|
text() |
Basic string sanitization with optional HTML stripping | $sanitizer->text('bio', true) |
email() |
Validates and sanitizes email addresses | $sanitizer->email('email') |
html() |
Escapes HTML special characters | $sanitizer->html('comment') |
number() |
Sanitizes integer values | $sanitizer->number('age') |
float() |
Sanitizes floating-point numbers | $sanitizer->float('price') |
boolean() |
Validates boolean values | $sanitizer->boolean('active') |
url() |
Sanitizes URLs | $sanitizer->url('website') |
ip() |
Validates IP addresses | $sanitizer->ip('ip_address') |
alpha() |
Only alphabetic characters | $sanitizer->alpha('first_name') |
alphaNum() |
Alphanumeric characters only | $sanitizer->alphaNum('username') |
alphaDash() |
Alphanumeric with dashes/underscores | $sanitizer->alphaDash('slug') |
digits() |
Digits only | $sanitizer->digits('pin') |
phone() |
Sanitizes phone numbers | $sanitizer->phone('phone') |
date() |
Validates and formats dates | $sanitizer->date('birthday', 'Y-m-d') |
json() |
Validates and optionally decodes JSON | $sanitizer->json('preferences', true) |
array() |
Sanitizes arrays with optional callback | $sanitizer->array('tags', 'trim') |
file() |
Sanitizes file upload data | $sanitizer->file('avatar') |
password() |
Sanitizes passwords with optional hashing | $sanitizer->password('password', true) |
safe() |
Removes dangerous content with allowed tags | $sanitizer->safe('content', ['p','b']) |
Advanced Features
Bulk Sanitization
// Sanitize multiple fields at once
$cleanData = $sanitizer->to([
'name' => 'text',
'email' => 'email',
'age' => 'number'
]);
Filtering Data
// Get only specific fields
$filtered = $sanitizer->only(['name', 'email']);
// Exclude specific fields
$filtered = $sanitizer->except(['password']);
Collection Conversion
// Convert to Collection for chaining
$sanitizer->collect('tags')->map(fn($tag) => strtoupper($tag));
Tip: Use the
__toString()
method to get the first sanitized text
value: (string)$sanitizer