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β
| Helper | Description |
|---|---|
| app | Accesses the dependency injection container |
| config | Retrieves or sets a configuration value |
| app_env | Retrieves an environment variable |
| app_assets | Generates the URL of an asset |
| app_abort | Interrupts execution with an HTTP error |
| app_abort_if | Interrupts execution if a condition is true |
| app_mode | Returns the application mode (dev, prod) |
| app_in_debug | Checks whether debug mode is enabled |
HTTP and Responsesβ
| Helper | Description |
|---|---|
| request | Accesses the current HTTP request |
| response | Creates an HTTP response |
| response_json | Returns a JSON response |
| response_download | Forces the download of a file |
| set_response_status_code | Sets the HTTP status code |
| set_response_header | Adds a header to the response |
| get_response_header | Retrieves a header from the response |
| redirect | Creates an HTTP redirect |
| redirect_back | Redirects to the previous page |
| url | Builds a URL |
| route | Generates the URL of a named route |
| old | Retrieves the old value of a field |
| view | Compiles and returns a view |
Databaseβ
| Helper | Description |
|---|---|
| db | Accesses the database instance |
| table | Returns a QueryBuilder for a table |
| app_db_table | Alias of table() |
| get_last_insert_id | Retrieves the last inserted ID |
| app_db_select | Executes a SELECT query |
| app_db_select_one | Retrieves a single record |
| app_db_insert | Inserts data |
| app_db_delete | Deletes records |
| app_db_update | Updates records |
| app_db_statement | Executes a raw SQL query |
| app_db_transaction | Starts a transaction |
| app_db_transaction_started | Checks whether a transaction is active |
| app_db_rollback | Rolls back the transaction |
| app_db_commit | Commits the transaction |
| pdo | Retrieves the PDO instance |
| set_pdo | Sets a new PDO instance |
| app_db_seed | Runs a seeder |
Securityβ
| Helper | Description |
|---|---|
| encrypt | Encrypts a string |
| decrypt | Decrypts a string |
| app_hash | Creates or verifies a hash |
| sanitize | Cleans a string (removes HTML tags) |
| secure | Escapes special characters |
| create_csrf_token | Creates a new CSRF token |
| csrf_token | Retrieves the current CSRF token |
| csrf_field | Generates a hidden field for the CSRF token |
| method_field | Generates a hidden field for the HTTP method |
| gen_csrf_token | Generates a CSRF token in the session |
| verify_csrf | Verifies a CSRF token |
| csrf_time_is_expired | Checks whether the CSRF token has expired |
Authenticationβ
| Helper | Description |
|---|---|
| app_auth | Accesses the authentication system |
| auth | Alias of app_auth() (deprecated) |
Session and Cookiesβ
| Helper | Description |
|---|---|
| session | Manipulates the session |
| cookie | Manipulates cookies |
| flash | Sets a flash message |
| app_flash | Alias of flash() |
Stringsβ
| Helper | Description |
|---|---|
| e | Escapes HTML tags |
| str_uuid | Generates a UUID |
| str_slug | Converts to a URL-friendly slug |
| str_is_mail | Checks whether it is a valid email |
| str_is_domain | Checks whether it is a valid domain |
| str_is_slug | Checks whether it is a valid slug |
| str_is_alpha | Checks whether it contains only letters |
| str_is_lower | Checks whether it is lowercase |
| str_is_upper | Checks whether it is uppercase |
| str_is_alpha_num | Checks whether it is alphanumeric |
| str_shuffle_words | Shuffles the words |
| str_wordily | Splits into an array of words |
| str_plural | Converts to plural |
| str_camel | Converts to camelCase |
| str_snake | Converts to snake_case |
| str_contains | Checks whether it contains a substring |
| str_capitalize | Capitalizes |
| str_random | Generates a random string |
| str_force_in_utf8 | Forces the output to UTF-8 |
| str_fix_utf8 | Fixes UTF-8 encoding |
Emailβ
| Helper | Description |
|---|---|
| Sends an email with a view | |
| app_email | Alias of email() |
| raw_email | Sends a raw email |
Events and Queuesβ
| Helper | Description |
|---|---|
| event | Emits an event |
| app_event | Alias of event() |
| queue | Adds a job to the queue |
Storage and Cacheβ
| Helper | Description |
|---|---|
| app_storage | Accesses a local storage disk |
| storage_service | Accesses a storage service (S3, FTP) |
| cache | Manipulates the cache |
Translationβ
| Helper | Description |
|---|---|
| app_trans | Translates a key |
| t | Alias of app_trans() |
| __ | Alias of app_trans() |
Validationβ
| Helper | Description |
|---|---|
| validator | Validates data |
Loggingβ
| Helper | Description |
|---|---|
| logger | Accesses the logger |
| app_logger | Alias of logger() |
Utilitiesβ
| Helper | Description |
|---|---|
| collect | Creates a collection |
| app_now | Returns the current date/time (Carbon) |
| client_locale | Retrieves the client's language |
| is_blank | Checks whether a value is empty |
| debug | Displays debugging information |
| sep | Returns 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>");
// "<script>alert('xss')</script>"
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 ofapp_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");
cookieβ
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>");
// <script>alert('xss')</script>
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.