Docs LATEST

Request

The Request class encapsulates HTTP request data and provides convenient methods for accessing input, headers, files, and metadata.

HTTP

Namespace: VelvetCMS\Http\Request


Definition #

class Request
{
    public function __construct();
    public static function capture(): self;
    
    // Request metadata
    public function method(): string;
    public function path(): string;
    public function rawPath(): string;
    public function url(): string;
    public function host(): string;
    public function isSecure(): bool;
    public function setPathPrefix(?string $prefix): void;
    
    // Input access
    public function input(string $key, mixed $default = null): mixed;
    public function all(): array;
    public function only(array $keys): array;
    public function except(array $keys): array;
    public function has(string $key): bool;
    public function query(string $key, mixed $default = null): mixed;
    public function post(string $key, mixed $default = null): mixed;
    
    // Files and cookies
    public function file(string $key): ?array;
    public function cookie(string $key, mixed $default = null): mixed;
    
    // Headers
    public function header(string $key, mixed $default = null): mixed;
    public function userAgent(): ?string;
    public function ip(): ?string;
    
    // Request type detection
    public function ajax(): bool;
    public function expectsJson(): bool;
    public function isJson(): bool;
    
    // Validation
    public function validate(array $rules): array;
}

Creating Requests #

capture() #

Create a Request instance from the current HTTP request.

public static function capture(): self

Example:

$request = Request::capture();

// Or use the helper
$request = request();

Request Metadata #

method() #

Get the HTTP request method.

public function method(): string

Returns: Uppercase method name (GET, POST, PUT, DELETE, PATCH).

Example:

$method = $request->method(); // "POST"

path() #

Get the request path (with optional prefix removed).

public function path(): string

Example:

// URL: https://example.com/blog/posts/hello-world?page=2
$request->path(); // "/blog/posts/hello-world"

rawPath() #

Get the original request path without prefix handling.

public function rawPath(): string

url() #

Get the full URL without query string.

public function url(): string

Example:

$request->url(); // "https://example.com/blog/posts"

host() #

Get the request host (without port).

public function host(): string

Example:

$request->host(); // "example.com"

isSecure() #

Check if the request uses HTTPS.

public function isSecure(): bool

setPathPrefix() #

Set a path prefix to strip from the path.

public function setPathPrefix(?string $prefix): void

Used for multi-tenant setups where each tenant has a URL prefix.


Input Access #

input() #

Get an input value from POST or GET data.

public function input(string $key, mixed $default = null): mixed
Parameter Type Description
$key string Input field name
$default mixed Default if not found

Example:

$name = $request->input('name');
$page = $request->input('page', 1);

all() #

Get all input data (merged POST and GET).

public function all(): array

Example:

$data = $request->all();
// ['name' => 'John', 'email' => 'john@example.com', 'page' => '1']

only() #

Get only specified input fields.

public function only(array $keys): array

Example:

$credentials = $request->only(['email', 'password']);
// ['email' => 'john@example.com', 'password' => 'secret']

except() #

Get all input except specified fields.

public function except(array $keys): array

Example:

$data = $request->except(['_token', '_method']);

has() #

Check if an input field exists.

public function has(string $key): bool

Example:

if ($request->has('remember')) {
    // Remember user login
}

query() #

Get a value from the query string only.

public function query(string $key, mixed $default = null): mixed

Example:

// URL: /posts?page=2&sort=date
$page = $request->query('page', 1); // 2
$sort = $request->query('sort');     // "date"

post() #

Get a value from POST data only.

public function post(string $key, mixed $default = null): mixed

Files and Cookies #

file() #

Get an uploaded file.

public function file(string $key): ?array

Returns: PHP file upload array or null.

Example:

$file = $request->file('avatar');

if ($file && $file['error'] === UPLOAD_ERR_OK) {
    $tmpPath = $file['tmp_name'];
    $originalName = $file['name'];
    $mimeType = $file['type'];
    $size = $file['size'];
    
    move_uploaded_file($tmpPath, storage_path("uploads/{$originalName}"));
}

Get a cookie value.

public function cookie(string $key, mixed $default = null): mixed

Example:

$theme = $request->cookie('theme', 'light');

Headers #

Get a request header.

public function header(string $key, mixed $default = null): mixed

Example:

$auth = $request->header('Authorization');
$contentType = $request->header('Content-Type');
$accept = $request->header('Accept', 'text/html');

userAgent() #

Get the User-Agent header.

public function userAgent(): ?string

ip() #

Get the client IP address.

public function ip(): ?string

Request Type Detection #

ajax() #

Check if the request is an AJAX request.

public function ajax(): bool

Checks for X-Requested-With: XMLHttpRequest header.


expectsJson() #

Check if the client expects JSON response.

public function expectsJson(): bool

Checks for application/json in Accept header.

Example:

if ($request->expectsJson()) {
    return Response::json(['error' => 'Not found'], 404);
}

return Response::html('<h1>Not Found</h1>', 404);

isJson() #

Check if the request content type is JSON.

public function isJson(): bool

When true, JSON request body is automatically parsed into POST data.


Validation #

validate() #

Validate input against rules.

public function validate(array $rules): array
Parameter Type Description
$rules array Validation rules

Returns: Validated data (only fields with rules).

Throws: ValidationException on failure.

Example:

try {
    $data = $request->validate([
        'title' => 'required|max:200',
        'email' => 'required|email',
        'status' => 'in:draft,published',
    ]);
    
    // $data contains only validated fields
    $page->update($data);
    
} catch (ValidationException $e) {
    return Response::json([
        'errors' => $e->errors()
    ], 422);
}

Usage Examples #

Form Processing #

public function store(Request $request): Response
{
    $data = $request->validate([
        'name' => 'required|min:2|max:100',
        'email' => 'required|email',
        'message' => 'required|max:1000',
    ]);
    
    $this->contactService->send($data);
    
    return redirect('/contact/thanks');
}

API Endpoint #

public function search(Request $request): Response
{
    $query = $request->input('q', '');
    $page = (int) $request->query('page', 1);
    $limit = min((int) $request->query('limit', 10), 100);
    
    $results = $this->searchService->search($query, $page, $limit);
    
    return Response::json([
        'data' => $results,
        'meta' => [
            'query' => $query,
            'page' => $page,
            'limit' => $limit,
        ]
    ]);
}

File Upload #

public function upload(Request $request): Response
{
    $file = $request->file('document');
    
    if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
        return Response::json(['error' => 'Upload failed'], 400);
    }
    
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = uniqid() . '.' . $extension;
    
    move_uploaded_file(
        $file['tmp_name'],
        storage_path("uploads/{$filename}")
    );
    
    return Response::json(['filename' => $filename]);
}