Skip to content

📥 HTTP Requests

The Request class in PageBlocks provides a simple yet powerful way to work with incoming HTTP requests. It wraps superglobal variables ($_GET, $_POST, $_FILES, $_SERVER, etc.) and offers a clean API for accessing data, headers, files, checking request type, and validation.

You can obtain a request instance in two ways:

🧩 Via Global Helper

php
request()               // Returns the Request instance
request('email')        // Immediately returns the value by key

The request() helper is a shortcut to get the current HTTP request or a specific parameter value.

⚙️ Via Dependency Injection in Closure

php
use Boshnik\PageBlocks\Http\Request;

Route::get('/', function (Request $request) {
    $email = $request->email;
});

The Request class is automatically injected into route closures or controllers when specified in parameters.

📍 Path and URL

path() — request path without domain

php
request()->path(); // '/catalog/items'

url() — current URL (without parameters)

php
request()->url(); // 'https://example.com/catalog/items'

fullUrl() — full request URL

php
request()->fullUrl(); // 'https://example.com/catalog/items?sort=price'

rootUrl() — site base URL

php
request()->rootUrl(); // 'https://example.com'

isSecure() — whether the request is secure (HTTPS)

php
request()->isSecure(); // true or false

📡 Request Method

method() — returns HTTP method (GET, POST, PUT...)

php
if (request()->method() === 'POST') {
    // form processing
}

isMethod() — checks request type

php
if (request()->isMethod('post')) {
    //...
}

🧾 Headers

header($key) — get a header

php
request()->header('Accept'); // 'text/html,application/xhtml+xml,...'

hasHeader($key) — check if header exists

php
request()->hasHeader('Authorization');

🌐 Client IP Address

php
request()->ip(); // e.g.: '192.168.1.10'

🔍 Checking Request Type

ajax() — is this an AJAX request?

php
if (request()->ajax()) {
    return json(['ok' => true]);
}

isJson() — does the request contain JSON?

php
request()->isJson(); // true if JSON in Content-Type or Accept

expectsJson() — does the client expect JSON response?

php
request()->expectsJson(); // true for API

accepts(array $types) — does the client support the required type?

php
request()->accepts(['application/json', 'text/html']);

📥 Getting Data

input($key) — get any input value (GET, POST, JSON, FILES)

php
request()->input('email');
request('email');

get($key, $default) — same as above

php
request()->get('email', 'no@email.com');

has($key) — does the value exist?

php
if (request()->has('token')) {
    // ...
}

💾 All Request Data

php
request()->all(); // returns array from query + post + json + files

✉️ Getting GET and POST

php
request()->query('id');     // $_GET['id']
request()->post('name');    // $_POST['name']

🧪 Getting JSON Data

If the request contains Content-Type: application/json, you can get:

php
request()->json('title');  // single value
request()->json();         // entire JSON

Example:

json
{
  "title": "Hello world",
  "tags": ["php", "modx"]
}

📁 Working with Files

hasFile($key) — was a file uploaded

php
if (request()->hasFile('avatar')) {
    // ...
}

file($key) — get uploaded file

php
$file = request()->file('avatar');
$file->moveTo('uploads/'); // example: UploadedFile method

files() — get all files

php
$all = request()->files(); // array of files

🧪 Data Validation

php
$data = request()->validate([
    'email' => 'required|email',
    'password' => 'required|min:6',
]);

If validation fails, an exception is thrown which can be caught to return an error to the client.

🔮 Magic Properties

You can access data directly as properties:

php
$name = request()->name;

request()->city = 'Kyiv';

🧰 Full Request Handling Example

php
public function store(Request $request)
{
    // Form data validation
    $validated = $request->validate([
        'honeypot'   => 'empty',
        'pagetitle'  => 'required|unique:modResource',
        'alias'      => 'nullable|string',
        'template'   => 'required|numeric|exists:modTemplate,id',
        'content'    => 'nullable|string',
    ]);

    // Merge with default MODX resource values
    $data = array_merge([
        'class_key'     => 'modDocument',
        'context_key'   => 'web',
        'content_type'  => 1,
        'published'     => 1,
        'publishedon'   => '',
        'publishedby'   => $this->modx->user->id ?? 1,
        'deleted'       => 0,
    ], $validated);

    // Save resource
    $status = query(\modResource::class)->create($data);

    return $status
        ? response()->success('Resource created successfully')
        : response()->error('Error creating resource');
}

📌 Summary

MethodDescription
request() or $request in controllerGet request instance
input(), get()Get value by key
all()All request data
method(), isMethod()Request method
header(), hasHeader()Headers
ip()Client IP
ajax(), isJson(), expectsJson()Request type
json()Request JSON body
file(), hasFile(), files()Working with files
validate()Input data validation

© PageBlocks 2019-present