Global Helper Functions
Introduction
Slenix ships with a comprehensive set of global helper functions available anywhere in your application — controllers, views, route closures, and Luna templates. These functions cover the most common tasks in web development: generating URLs, managing sessions, flashing messages, redirecting users, working with arrays, encoding data, and more.
You do not need to import or instantiate anything. Just call the function.
Environment
env()
Retrieves a value from the environment (.env file, $_ENV, or $_SERVER). Automatically casts the strings "true", "false", and "null" to their native PHP types.
$debug = env('APP_DEBUG'); // true or false (cast from string)
$name = env('APP_NAME', 'App'); // second argument is the defaultconfig()
A convenience wrapper around env() that accepts dot-notation keys and converts them to uppercase environment variable names.
config('app.debug') // reads env('APP_DEBUG')
config('db.host') // reads env('DB_HOST')app_env()
Returns true if the current APP_ENV matches any of the given environment names.
if (app_env('production')) {
// only in production
}
if (app_env('local', 'testing')) {
// in local or testing
}is_debug()
Returns true when APP_DEBUG is enabled.
if (is_debug()) {
dump($query);
}Paths
These functions return absolute paths within your project. Each accepts an optional relative path that is appended to the base directory.
base_path(); // /var/www/myapp
base_path('composer.json'); // /var/www/myapp/composer.json
app_path('Models/User.php'); // /var/www/myapp/app/Models/User.php
public_path('css/app.css'); // /var/www/myapp/public/css/app.css
storage_path('logs/app.log'); // /var/www/myapp/storage/logs/app.log
views_path('auth/login.luna'); // /var/www/myapp/views/auth/login.luna| Function | Base constant |
|---|---|
base_path() | ROOT_PATH |
app_path() | APP_PATH |
public_path() | PUBLIC_PATH |
storage_path() | STORAGE_PATH |
views_path() | VIEWS_PATH |
Views
view()
Renders a Luna template and sends the output directly to the browser.
view('home.index');
view('user.profile', [
'user' => $user,
'posts' => $posts,
]);Redirects
redirect()
Returns a fluent RedirectResponse object. The redirect is only sent when a terminal method such as to(), back(), or route() is called.
// Redirect to an explicit URL
redirect('/dashboard');
// Redirect back to the previous page
redirect()->back();
// Redirect to a named route
redirect()->route('login');
// Redirect with a fallback if the referer is not available
redirect()->back('/home');Chaining Flash Data
You can attach data to the session before redirecting by chaining methods onto the response object. The data is available on the next request.
redirect('/profile')
->with('success', 'Profile updated.')
->withInput()
->withErrors(['name' => 'The name field is required.']);| Method | Description |
|---|---|
with(key, value) | Flashes a single key-value pair to the session |
withMany(array) | Flashes multiple key-value pairs at once |
withErrors(array, bag?) | Flashes validation errors, optionally grouped by bag name |
withInput(array?) | Flashes the current $_POST data (sensitive fields removed automatically) |
Flash Messages
flash()
Returns a FlashMessage instance for writing and reading flash data between requests.
Writing flash messages:
flash()->success('Your changes have been saved.');
flash()->error('Something went wrong. Please try again.');
flash()->warning('Your session is about to expire.');
flash()->info('A new version is available.');
// Custom key
flash()->write('verification_sent', true);Reading flash messages in the next request:
if (flash()->has('success')) {
echo flash()->get('success');
}
// Shorthand — type aliases work with or without the _flash_ prefix
flash()->get('error'); // resolves _flash_error
flash()->get('warning'); // resolves _flash_warning
// Get everything at once (non-destructive)
$all = flash()->all();In Luna templates the flash() helper is shared automatically:
@if ($flash->has('success'))
<div class="alert alert-success">{{ $flash->get('success') }}</div>
@endifSession
session()
Provides a flexible interface for reading and writing session values.
// Retrieve a value
$userId = session('user_id');
// Store a value
session('theme', 'dark');
// Store multiple values at once
session(['locale' => 'en', 'timezone' => 'UTC']);
// Retrieve the fluent SessionManager instance
session()->put('cart', $items);
session()->forget('cart');The SessionManager object returned by session() exposes the following methods:
| Method | Description | |
|---|---|---|
set(key, value) | Stores a value in the session | |
| `put(key\ | array, value?)` | Stores one or multiple values |
get(key, default?) | Retrieves a value | |
has(key) | Returns true if the key exists | |
missing(key) | Returns true if the key does not exist | |
pull(key, default?) | Retrieves and removes a value in one call | |
| `forget(key\ | array)` | Removes one or multiple keys |
flush() | Clears all session data without destroying the session | |
invalidate() | Destroys the session completely | |
regenerate(deleteOld?) | Regenerates the session ID (call after login/logout) | |
flash(key, value) | Writes a flash value | |
getFlash(key, default?) | Reads and removes a flash value | |
hasFlash(key) | Checks whether a flash value exists | |
flashInput(array) | Flashes form input for repopulation | |
increment(key, amount?) | Increments a numeric value | |
decrement(key, amount?) | Decrements a numeric value | |
push(key, value) | Appends a value to an array stored in the session | |
id() | Returns the current session ID | |
all() | Returns the entire session as an array |
Forms — Old Input & Validation Errors
old()
Returns the previously submitted value of a form field. This is populated by redirect()->withInput() or session()->flashInput().
old('email'); // returns the old value or empty string
old('name', 'Guest'); // returns 'Guest' if no old value existsIn Luna templates:
<input type="email" name="email" value="@old('email')">errors()
Returns validation errors stored by redirect()->withErrors().
// All errors across all bags
errors();
// The first error message for a specific field
errors('email'); // returns string|null
// All error messages for a specific field
errors('email', true); // returns arrayhas_error()
Returns true if the given field has at least one validation error.
has_error('email');In Luna templates you can use these to conditionally apply CSS classes or display inline error messages:
<input
type="text"
name="name"
class="{{ has_error('name') ? 'is-invalid' : '' }}"
value="@old('name')"
>
@if (has_error('name'))
<span class="error">{{ errors('name') }}</span>
@endifURLs & Routes
url()
Generates an absolute URL using APP_BASE_URL as the base. Accepts an optional query-string array.
url('/about'); // https://example.com/about
url('/search', ['q' => 'slenix']); // https://example.com/search?q=slenixasset()
An alias for url(). Use it for static files served from your public directory.
asset('css/app.css'); // https://example.com/css/app.css
asset('js/main.js');route()
Generates a URL for a named route, optionally substituting route parameters.
route('home');
route('user.show', ['id' => 42]); // https://example.com/users/42current_url()
Returns the full URL of the current request, including query string.
current_url(); // https://example.com/dashboard?tab=settingsrequest_path()
Returns only the path of the current request, without the query string.
request_path(); // /dashboardis_active()
Checks whether the current request path matches a pattern. Useful for highlighting active navigation items.
is_active('/home'); // exact match
is_active('/blog/*'); // wildcard — matches /blog/any-post
// Returns the second argument on match, third on no match
is_active('/dashboard', 'active', '');In Luna templates:
<a href="/dashboard" class="{{ is_active('/dashboard', 'active') }}">Dashboard</a>HTTP Responses
response()
Creates a Response object. Can be used as a factory for building responses.
return response('Not Found', 404);
return response(json_encode($data), 200);abort()
Immediately terminates the request with the given HTTP status code. Automatically renders a JSON response when the client sends an Accept: application/json header, and an HTML error page otherwise.
abort(404);
abort(403, 'You do not have permission to access this resource.');abort_if()
Calls abort() only when the given condition is true.
abort_if($user->isBanned(), 403);
abort_if(!$post->exists, 404, 'Post not found.');abort_unless()
Calls abort() only when the given condition is false.
abort_unless($user->isAdmin(), 403);
abort_unless($token->isValid(), 401, 'Invalid token.');Security
csrf_token()
Returns the current session's CSRF token as a raw string, generating one automatically if it does not yet exist.
$token = csrf_token();csrf_field()
Returns a complete <input type="hidden"> element containing the CSRF token. Equivalent to the @csrf Luna directive.
echo csrf_field();
// <input type="hidden" name="_csrf_token" value="...">method_field()
Returns a hidden input that signals the intended HTTP method. Used in HTML forms that must simulate PUT, PATCH, or DELETE.
echo method_field('PUT');
// <input type="hidden" name="_method" value="PUT">In Luna templates:
<form method="POST" action="{{ route('post.update', ['id' => $post->id]) }}">
@csrf
@method('PUT')
...
</form>encrypt() / decrypt()
Encrypt and decrypt strings using AES-256-GCM with your application's APP_KEY.
$cipher = encrypt('sensitive value');
$plain = decrypt($cipher); // 'sensitive value'Note:
decrypt()returnsfalseif the ciphertext is invalid or has been tampered with.
hash_make() / hash_check()
Hashes a password using bcrypt with a cost of 12, and verifies a password against its stored hash.
$hash = hash_make('secret-password');
if (hash_check('secret-password', $hash)) {
// password is correct
}Strings
sanitize()
Trims whitespace and escapes HTML special characters.
sanitize(' <script>alert(1)</script> ');
// '<script>alert(1)</script>'validate_name()
Returns true if the string contains only Unicode letters and spaces (supports accented characters).
validate_name('Cláudio Silva'); // true
validate_name('cl4udio!'); // falsecamel_case() / snake_case() / pascal_case() / kebab_case()
Convert strings between common naming conventions.
camel_case('foo_bar_baz'); // 'fooBarBaz'
snake_case('FooBarBaz'); // 'foo_bar_baz'
pascal_case('foo-bar-baz'); // 'FooBarBaz'
kebab_case('FooBarBaz'); // 'foo-bar-baz'str_default()
Returns the string as-is, or the default if the string is empty or null.
str_default('', 'Anonymous'); // 'Anonymous'
str_default('Claudio', 'Anonymous'); // 'Claudio'limit()
Truncates a string to the given character length, appending a suffix.
limit('Hello, World!', 7); // 'Hello, ...'
limit('Hello, World!', 7, ' →'); // 'Hello, →'str_slug()
Converts a string into a URL-friendly slug.
str_slug('Olá, Mundo!'); // 'ola-mundo'
str_slug('Hello World', '_'); // 'hello_world'str_contains_any()
Returns true if the string contains at least one of the values in the given array.
str_contains_any('Hello World', ['World', 'Earth']); // true
str_contains_any('Hello World', ['Mars', 'Venus']); // falsemask()
Replaces part of a string with a repeating character.
mask('joao@email.com', '*', 2, 8); // 'jo********mail.com'
mask('4111111111111111', '*', 0, 12); // '************1111'Arrays
is_empty()
Returns true if the value is null, an empty string, or an empty array.
is_empty(null); // true
is_empty(''); // true
is_empty([]); // true
is_empty(0); // falsearray_get()
Retrieves a value from a nested array using dot-notation. Returns the default if the key does not exist.
$data = ['user' => ['address' => ['city' => 'Luanda']]];
array_get($data, 'user.address.city'); // 'Luanda'
array_get($data, 'user.address.zip', 'N/A'); // 'N/A'array_set()
Sets a value in a nested array using dot-notation, creating intermediate keys as needed.
$data = [];
array_set($data, 'user.address.city', 'Luanda');
// $data = ['user' => ['address' => ['city' => 'Luanda']]]array_only()
Returns a new array containing only the specified keys.
array_only(['name' => 'Ana', 'email' => 'ana@x.com', 'password' => '...'], ['name', 'email']);
// ['name' => 'Ana', 'email' => 'ana@x.com']array_except()
Returns a new array with the specified keys removed.
array_except(['name' => 'Ana', 'password' => '...'], ['password']);
// ['name' => 'Ana']array_flatten()
Collapses a multi-dimensional array into a single flat array.
array_flatten([[1, 2], [3, [4, 5]]]);
// [1, 2, 3, 4, 5]array_wrap()
Ensures a value is always an array. Wraps non-array values, returns empty array for null.
array_wrap('hello'); // ['hello']
array_wrap(['hello']); // ['hello']
array_wrap(null); // []collect()
Wraps an array in a fluent Collection object with chainable methods.
$users = collect($userArray)
->filter(fn($u) => $u['active'])
->sortBy('name')
->pluck('email')
->take(10)
->all();Available Collection methods:
| Method | Description |
|---|---|
all() | Returns the underlying array |
count() | Number of items |
isEmpty() / isNotEmpty() | Emptiness checks |
first(default?) / last(default?) | Access first or last item |
map(callback) | Transforms each item |
filter(callback?) | Filters items, re-indexes result |
each(callback) | Iterates without transforming |
pluck(key) | Extracts a column by key |
where(key, value) | Filters by key-value equality |
sortBy(key, direction?) | Sorts by a key (asc or desc) |
unique(key?) | Removes duplicate values or rows |
chunk(size) | Splits into chunks of the given size |
take(limit) | Returns the first N items |
skip(count) | Skips the first N items |
contains(value) | Checks for strict membership |
sum(key?) | Sums values or a column |
avg(key?) | Averages values or a column |
push(item) | Appends an item |
merge(array) | Merges another array |
keys() / values() | Returns keys or re-indexed values |
reverse() | Reverses item order |
shuffle() | Randomly shuffles items |
paginate(perPage, page?) | Slices for pagination and returns metadata |
toArray() | Alias for all() |
toJson() | JSON-encodes the collection |
JSON
to_json()
Encodes a value to a pretty-printed, UTF-8-safe JSON string.
to_json(['name' => 'Cláudio', 'active' => true]);from_json()
Decodes a JSON string, returning an associative array by default.
$data = from_json('{"name":"Cláudio"}');
$data['name']; // 'Cláudio'
// Return as stdClass
from_json('{"name":"Cláudio"}', false);Dates
now()
Returns the current date and time as a DateTimeImmutable instance.
$date = now();
echo $date->format('Y-m-d H:i:s');format_date()
Parses a date string and formats it. Returns null if parsing fails.
format_date('2025-01-15', 'd/m/Y'); // '15/01/2025'
format_date('2025-01-15 14:30:00'); // '15/01/2025 14:30:00'
format_date('not-a-date'); // nullhuman_date()
Converts a date into a human-readable relative string in Portuguese.
human_date('2025-01-14 10:00:00'); // 'há 3 dias'
human_date(now()->modify('-2 hours')); // 'há 2 horas'Debug
dd()
Dumps one or more values with styled output and immediately terminates execution.
dd($user, $request, $config);dump()
Same as dd() but does not stop execution.
dump($user);
// execution continuesbenchmark()
Returns the number of milliseconds elapsed since the application started (SLENIX_START).
echo benchmark() . ' ms';Luna Template Sharing
All helpers are automatically shared with Luna templates. The following variables are injected into every template without any extra configuration:
| Variable | Type | Description |
|---|---|---|
$route | Closure | Calls route(name, params) |
$csrf_token | Closure | Returns the CSRF token string |
$csrf_field | Closure | Returns the hidden CSRF input |
$old | Closure | Returns old form input |
$errors | Closure | Returns validation errors |
$has_error | Closure | Checks if a field has an error |
$flash | FlashMessage | Flash message instance |
$is_active | Closure | Checks active route pattern |
$asset | Closure | Generates an asset URL |
$url | Closure | Generates a full URL |
$Session | array | Array of session method closures |
The $Session array exposes: has, get, set, flash, getFlash, hasFlash, remove, all, and destroy.