Skip to main content
Version: 5.x

Global PHP Helpers

Introduction​

Helpers are global functions that simplify common tasks in BowPHP. These shortcut functions let you quickly access the framework's features without having to instantiate classes or inject dependencies.

List of helpers​

Application​

HelperDescription
appAccesses the dependency injection container
configRetrieves or sets a configuration value
app_envRetrieves an environment variable
app_assetsGenerates the URL of an asset
app_abortInterrupts execution with an HTTP error
app_abort_ifInterrupts execution if a condition is true
app_modeReturns the application mode (dev, prod)
app_in_debugChecks whether debug mode is enabled

HTTP and Responses​

HelperDescription
requestAccesses the current HTTP request
responseCreates an HTTP response
response_jsonReturns a JSON response
response_downloadForces the download of a file
set_response_status_codeSets the HTTP status code
set_response_headerAdds a header to the response
get_response_headerRetrieves a header from the response
redirectCreates an HTTP redirect
redirect_backRedirects to the previous page
urlBuilds a URL
routeGenerates the URL of a named route
oldRetrieves the old value of a field
viewCompiles and returns a view

Database​

HelperDescription
dbAccesses the database instance
tableReturns a QueryBuilder for a table
app_db_tableAlias of table()
get_last_insert_idRetrieves the last inserted ID
app_db_selectExecutes a SELECT query
app_db_select_oneRetrieves a single record
app_db_insertInserts data
app_db_deleteDeletes records
app_db_updateUpdates records
app_db_statementExecutes a raw SQL query
app_db_transactionStarts a transaction
app_db_transaction_startedChecks whether a transaction is active
app_db_rollbackRolls back the transaction
app_db_commitCommits the transaction
pdoRetrieves the PDO instance
set_pdoSets a new PDO instance
app_db_seedRuns a seeder

Security​

HelperDescription
encryptEncrypts a string
decryptDecrypts a string
app_hashCreates or verifies a hash
sanitizeCleans a string (removes HTML tags)
secureEscapes special characters
create_csrf_tokenCreates a new CSRF token
csrf_tokenRetrieves the current CSRF token
csrf_fieldGenerates a hidden field for the CSRF token
method_fieldGenerates a hidden field for the HTTP method
gen_csrf_tokenGenerates a CSRF token in the session
verify_csrfVerifies a CSRF token
csrf_time_is_expiredChecks whether the CSRF token has expired

Authentication​

HelperDescription
app_authAccesses the authentication system
authAlias of app_auth() (deprecated)

Session and Cookies​

HelperDescription
sessionManipulates the session
cookieManipulates cookies
flashSets a flash message
app_flashAlias of flash()

Strings​

HelperDescription
eEscapes HTML tags
str_uuidGenerates a UUID
str_slugConverts to a URL-friendly slug
str_is_mailChecks whether it is a valid email
str_is_domainChecks whether it is a valid domain
str_is_slugChecks whether it is a valid slug
str_is_alphaChecks whether it contains only letters
str_is_lowerChecks whether it is lowercase
str_is_upperChecks whether it is uppercase
str_is_alpha_numChecks whether it is alphanumeric
str_shuffle_wordsShuffles the words
str_wordilySplits into an array of words
str_pluralConverts to plural
str_camelConverts to camelCase
str_snakeConverts to snake_case
str_containsChecks whether it contains a substring
str_capitalizeCapitalizes
str_randomGenerates a random string
str_force_in_utf8Forces the output to UTF-8
str_fix_utf8Fixes UTF-8 encoding

Email​

HelperDescription
emailSends an email with a view
app_emailAlias of email()
raw_emailSends a raw email

Events and Queues​

HelperDescription
eventEmits an event
app_eventAlias of event()
queueAdds a job to the queue

Storage and Cache​

HelperDescription
app_storageAccesses a local storage disk
storage_serviceAccesses a storage service (S3, FTP)
cacheManipulates the cache

Translation​

HelperDescription
app_transTranslates a key
tAlias of app_trans()
__Alias of app_trans()

Validation​

HelperDescription
validatorValidates data

Logging​

HelperDescription
loggerAccesses the logger
app_loggerAlias of logger()

Utilities​

HelperDescription
collectCreates a collection
app_nowReturns the current date/time (Carbon)
client_localeRetrieves the client's language
is_blankChecks whether a value is empty
debugDisplays debugging information
sepReturns the directory separator

Application​

app​

Accesses BowPHP's dependency injection container.

// Retrieve a service
$mailer = app("mail");

// Retrieve a class with auto-resolution
$service = app(UserService::class);

// Without an argument, returns the container
$container = app();

config​

Retrieves or sets a configuration value.

// Retrieve a configuration value
$driver = config("database.driver");

// With a default value
$timeout = config("app.timeout", 30);

// Retrieve an entire section
$mailConfig = config("mail");

app_env​

Retrieves an environment variable defined in the .env file.

$appUrl = app_env("APP_URL");

// With a default value
$debug = app_env("APP_DEBUG", false);

app_assets​

Generates the full URL of an asset (CSS, JS, image).

$cssUrl = app_assets("css/style.css");
// /assets/css/style.css

$jsUrl = app_assets("js/app.js");
// /assets/js/app.js

app_abort​

Interrupts the application's execution with an HTTP error.

// 404 error
app_abort(404);

// 403 error with a custom message
app_abort(403, "Access denied");

app_abort_if​

Interrupts execution if a condition is true.

$user = User::find($id);

// Returns 404 if the user does not exist
app_abort_if($user === null, 404, "User not found");

// Returns 403 if unauthorized
app_abort_if(!$user->canEdit($post), 403);

app_mode​

Returns the application mode (production, development, testing).

$mode = app_mode();

if ($mode === "development") {
// Development code
}

app_in_debug​

Checks whether the application is in debug mode.

if (app_in_debug()) {
// Display debugging information
var_dump($data);
}

HTTP and Responses​

request​

Accesses the instance of the current HTTP request.

// Retrieve a parameter
$name = request()->get("name");

// Retrieve all parameters
$all = request()->all();

// Check the HTTP method
if (request()->isPost()) {
// ...
}

// Retrieve an uploaded file
$file = request()->file("avatar");

response​

Creates an HTTP response.

// Simple response
return response("Hello World");

// With a status code
return response("Not Found", 404);

// Access the Response instance
return response()->status(201)->send("Created");

response_json​

Returns a response in JSON format.

return response_json(["name" => "John", "age" => 25]);

// With a status code
return response_json(["error" => "Not found"], 404);

response_download​

Forces the download of a file.

$filepath = storage_path("files/document.pdf");

// Download with the original name
return response_download($filepath);

// Download with a custom name
return response_download($filepath, "my-document.pdf");

set_response_status_code​

Sets the HTTP status code of the response.

set_response_status_code(201); // Created
set_response_status_code(404); // Not Found

set_response_header​

Adds a header to the HTTP response.

set_response_header("X-Custom-Header", "value");
set_response_header("Cache-Control", "no-cache");

get_response_header​

Retrieves a header from the HTTP response.

$contentType = get_response_header("Content-Type");

redirect​

Creates an HTTP redirect.

// Simple redirect
return redirect("/dashboard");

// With chained methods
return redirect()->to("/home");
return redirect()->route("user.profile", ["id" => 1]);

// With flash data
return redirect("/login")->with("error", "Session expired");

redirect_back​

Redirects to the previous page.

// Standard redirect
return redirect_back();

// With a custom status code
return redirect_back(301);

// With data
return redirect()->back()->with("message", "Saved");

url​

Builds a full URL.

// Simple URL
$url = url("/users");
// http://your-site.com/users

// With query parameters
$url = url("/users", ["page" => 2, "sort" => "name"]);
// http://your-site.com/users?page=2&sort=name

route​

Generates the URL of a named route.

// Route: Route::get('/users/:id', [UserController::class, 'show'])->name('user.show');
$url = route("user.show", ["id" => 1]);
// /users/1

// Absolute URL
$url = route("user.show", ["id" => 1], true);
// http://your-site.com/users/1

// With optional parameters
$url = route("search", ["q" => "bow", "page" => 2]);

old​

Retrieves the old value of a field after a redirect (useful for forms).

// In a view after failed validation
<input type="text" name="email" value="{{ old('email') }}">

// With a default value
$email = old("email", "default@example.com");

view​

Compiles and returns a view.

// Simple view
return view("home");

// With data
return view("users.profile", ["user" => $user]);

// With a status code
return view("errors.404", [], 404);

Database​

db​

Accesses the database connection instance.

$db = db();

// Execute a query
$users = db()->select("SELECT * FROM users WHERE active = ?", [1]);

table​

Returns a QueryBuilder for a specific table.

// Select all records
$users = table("users")->get();

// With conditions
$user = table("users")
->where("email", "john@example.com")
->first();

// Insertion
table("users")->insert([
"name" => "John",
"email" => "john@example.com"
]);

app_db_table​

Alias of table().

$users = app_db_table("users")->get();

get_last_insert_id​

Retrieves the last auto-incremented ID after an insertion.

table("users")->insert(["name" => "John"]);
$id = get_last_insert_id();

app_db_select​

Executes a SELECT query with parameters.

$users = app_db_select(
"SELECT * FROM users WHERE role = ?",
["admin"]
);

app_db_select_one​

Retrieves a single record.

$user = app_db_select_one(
"SELECT * FROM users WHERE id = ?",
[1]
);

app_db_insert​

Inserts data into a table.

$result = app_db_insert(
"INSERT INTO users (name, email) VALUES (?, ?)",
["John", "john@example.com"]
);

app_db_update​

Updates records.

$affected = app_db_update(
"UPDATE users SET name = ? WHERE id = ?",
["Jane", 1]
);

app_db_delete​

Deletes records.

$deleted = app_db_delete(
"DELETE FROM users WHERE id = ?",
[1]
);

app_db_statement​

Executes a raw SQL query (CREATE, ALTER, DROP, etc.).

app_db_statement("TRUNCATE TABLE users");
app_db_statement("ALTER TABLE users ADD COLUMN avatar VARCHAR(255)");

Transactions​

// Start a transaction
app_db_transaction();

try {
table("accounts")->where("id", 1)->decrement("balance", 100);
table("accounts")->where("id", 2)->increment("balance", 100);

// Commit
app_db_commit();
} catch (Exception $e) {
// Roll back
app_db_rollback();
throw $e;
}

// Check whether a transaction is active
if (app_db_transaction_started()) {
// ...
}

pdo / set_pdo​

Accesses or sets the PDO instance.

// Retrieve the PDO instance
$pdo = pdo();

// Set a new connection
$newPdo = new PDO($dsn, $user, $password);
set_pdo($newPdo);

app_db_seed​

Runs a seeder programmatically.

// By file name (seeders/users.php)
app_db_seed("users");

// With additional data
app_db_seed("users", ["created_by" => "admin"]);

// With a Model class
app_db_seed(User::class, ["name" => "John Doe"]);

Security​

encrypt / decrypt​

Encrypts and decrypts data.

// Encrypt
$encrypted = encrypt("sensitive data");

// Decrypt
$decrypted = decrypt($encrypted);
// "sensitive data"

app_hash​

Creates a hash or verifies an existing hash.

// Create a hash
$hash = app_hash("password123");

// Verify a hash
$isValid = app_hash("password123", $hash);
// true or false

sanitize​

Cleans a string by removing HTML tags and dangerous characters.

$clean = sanitize("<script>alert('xss')</script>Hello");
// "Hello"

$clean = sanitize("O'Reilly");
// "OReilly"

secure​

Escapes HTML special characters.

$safe = secure("<script>alert('xss')</script>");
// "&lt;script&gt;alert('xss')&lt;/script&gt;"

CSRF Protection​

// Generate a new CSRF token
create_csrf_token();

// Retrieve the current token
$token = csrf_token();

// Generate a hidden HTML field
echo csrf_field();
// <input type="hidden" name="_token" value="...">

// Verify a token
if (verify_csrf($tokenFromRequest)) {
// Valid token
}

// Check whether the token has expired
if (csrf_time_is_expired()) {
// Expired token
}

method_field​

Generates a hidden field to simulate the PUT, PATCH, and DELETE methods.

echo method_field("DELETE");
// <input type="hidden" name="_method" value="DELETE">

echo method_field("PUT");
// <input type="hidden" name="_method" value="PUT">

Authentication​

app_auth​

Accesses the authentication system.

// Check whether authenticated
if (app_auth()->check()) {
$user = app_auth()->user();
}

// With a specific guard
$admin = app_auth("admin")->user();

// Retrieve the user's ID
$userId = app_auth()->id();

// Log out
app_auth()->logout();

Note: auth() is a deprecated alias of app_auth().


Session and Cookies​

session​

Manipulates session data.

// Retrieve a value
$name = session("user_name");

// With a default value
$role = session("role", "guest");

// Retrieve the session instance
$session = session();
$session->set("key", "value");

Manipulates cookies.

// Retrieve a cookie
$value = cookie("remember_token");

// Set a cookie (expiration in seconds)
cookie("theme", "dark", 3600 * 24 * 30); // 30 days

// Retrieve all cookies
$all = cookie();

flash​

Sets a flash message (visible only once).

// Set a flash message
flash("success", "User created successfully");

// In the next view
$message = session("success");

Strings​

e​

Escapes HTML characters to prevent XSS injections.

$safe = e("<script>alert('xss')</script>");
// &lt;script&gt;alert('xss')&lt;/script&gt;

str_uuid​

Generates a UUID v4.

$uuid = str_uuid();
// "550e8400-e29b-41d4-a716-446655440000"

str_slug​

Converts a string into a URL-friendly slug.

$slug = str_slug("Hello World!");
// "hello-world"

// With a custom separator
$slug = str_slug("Hello World!", "_");
// "hello_world"

String checks​

str_is_mail("user@example.com"); // true
str_is_domain("example.com"); // true
str_is_slug("hello-world"); // true
str_is_alpha("Hello"); // true
str_is_lower("hello"); // true
str_is_upper("HELLO"); // true
str_is_alpha_num("Hello123"); // true

String transformations​

str_camel("hello_world");     // "helloWorld"
str_snake("helloWorld"); // "hello_world"
str_plural("user"); // "users"
str_capitalize("hello"); // "Hello"
str_shuffle_words("a b c"); // "c a b" (random)

Other string functions​

// Check whether it contains
str_contains("Hello World", "World"); // true

// Split into words
str_wordily("Hello World"); // ["Hello", "World"]

// Random string
str_random(16); // "a1b2c3d4e5f6g7h8"

// UTF-8
str_force_in_utf8();
$fixed = str_fix_utf8($brokenString);

Email​

email​

Sends an email with a template view.

email("emails.welcome", ["user" => $user], function ($mail) {
$mail->to("user@example.com")
->subject("Welcome to our site");
});

// Retrieve the Mail instance
$mailer = email();
$mailer->to("admin@example.com")
->subject("Notification")
->send("emails.notification", $data);

raw_email​

Sends a raw email without a template.

raw_email(
"user@example.com",
"Email subject",
"Plain text message body",
["From: no-reply@example.com"]
);

Events and Queues​

event​

Emits an event.

// Emit an event
event(UserRegistered::class, $user);

// With data
event("user.created", ["user" => $user, "timestamp" => time()]);

queue​

Adds a job to the queue.

queue(new SendWelcomeEmail($user));
queue(new ProcessPayment($order));

Storage and Cache​

app_storage​

Accesses a local storage disk.

$storage = app_storage("local");

// Write a file
$storage->put("documents/file.txt", $content);

// Read a file
$content = $storage->get("documents/file.txt");

// Check existence
if ($storage->exists("documents/file.txt")) {
// ...
}

storage_service​

Accesses a remote storage service (S3, FTP).

// S3 service
$s3 = storage_service("s3");
$s3->put("backups/db.sql", $backup);

// FTP service
$ftp = storage_service("ftp");
$ftp->download("remote/file.zip", "local/file.zip");

cache​

Manipulates the application cache.

// Retrieve a value
$value = cache("key");

// Set a value (TTL in seconds)
cache("key", "value", 3600); // 1 hour

// Retrieve the Cache instance
$cache = cache();
$cache->forget("key"); // Remove
$cache->flush(); // Clear the entire cache

Translation​

app_trans / t / __​

Translates a translation key.

// Simple translation
echo app_trans("messages.welcome");
// "Welcome"

// Aliases
echo t("messages.welcome");
echo __("messages.welcome");

// With variables
echo t("messages.hello", ["name" => "John"]);
// "Hello John"

// With plural choice
echo t("messages.items", [], true);

Validation​

validator​

Validates data against defined rules.

$validation = validator(
["email" => "test@example.com", "age" => 25],
["email" => "required|email", "age" => "required|int|min:18"]
);

if ($validation->fails()) {
$errors = $validation->getErrors();
return response_json(["errors" => $errors], 422);
}

// Validated data
$data = $validation->getData();

Logging​

logger / app_logger​

Accesses the logging system.

logger()->info("User logged in", ["user_id" => 1]);
logger()->warning("Slow query detected", ["time" => 2.5]);
logger()->error("Database error", ["exception" => $e->getMessage()]);

// Available levels: debug, info, notice, warning, error, critical, alert, emergency

Utilities​

collect​

Creates a collection from an array.

$collection = collect([1, 2, 3, 4, 5]);

$filtered = $collection->filter(fn($n) => $n > 2)->map(fn($n) => $n * 2);
// [6, 8, 10]

app_now​

Returns the current date/time as a Carbon instance.

$now = app_now();
echo $now->format("Y-m-d H:i:s");
// "2025-01-15 14:30:00"

echo $now->addDays(7)->format("Y-m-d");
// "2025-01-22"

client_locale​

Retrieves the client's preferred language from the Accept-Language header.

$locale = client_locale();
// "fr", "en", "es", etc.

is_blank​

Checks whether a value is "empty".

is_blank(null);      // true
is_blank(""); // true
is_blank(" "); // true
is_blank([]); // true
is_blank(0); // false
is_blank(false); // false
is_blank("hello"); // false

debug​

Displays formatted debugging information.

debug($variable);
debug($user, $request, $config);

sep​

Returns the system's directory separator.

$sep = sep();
// "/" on Linux/macOS, "\" on Windows

Source code​

https://github.com/bowphp/framework/blob/5.x/src/Support/helpers.php

Is something missing?

If you run into problems with the documentation or have suggestions to improve the documentation or the project in general, please open an issue for us, or send a tweet mentioning the Twitter account @bowframework or directly on github.