Helpers & Utilities
Helper Functions
The framework provides numerous helper functions to simplify common tasks. These functions are globally available throughout your application.
Application Helpers
Function | Description | Example |
---|---|---|
app() |
Get application instance or resolve service | app()->getPath() |
get() |
Resolve class from container | get(Logger::class) |
bind() |
Register binding in container | bind(Interface::class, Implementation::class) |
singleton() |
Register singleton in container | singleton(Logger::class) |
config() |
Get/set configuration values | config('app.name') |
abort() |
Abort request with error | abort(404) |
dump() |
Dump variable with syntax highlighting | dump($variable) |
HTTP Helpers
Function | Description | Example |
---|---|---|
request() |
Get request instance or input | request('username') |
response() |
Create or get response instance | response()->json($data) |
redirect() |
Redirect to URL | redirect('/dashboard') |
session() |
Get/set session data | session('user_id', 123) |
cookie() |
Get/set cookies | cookie('prefs', $prefs) |
input() |
Get sanitized input | input(['username', 'email']) |
validator() |
Validate input data | validator($rules, $data) |
errors() |
Get validation errors | errors()->any() |
old() |
Get old input value | old('email') |
Routing & URLs
Function | Description | Example |
---|---|---|
router() |
Get router instance | router()->get('/', fn() => ...) |
url() |
Generate absolute URL | url('path/to/resource') |
asset_url() |
Generate asset URL | asset_url('css/app.css') |
media_url() |
Generate media URL | media_url('uploads/image.jpg') |
route_url() |
Generate URL for named route | route_url('profile', ['id' => 1]) |
Database
Function | Description | Example |
---|---|---|
database() |
Get database instance | database()->query(...) |
db() |
Alias for database() | db()->table('users') |
query() |
Start new query | query('users')->where(...) |
Views & Assets
Function | Description | Example |
---|---|---|
view() |
Render view template | view('welcome', $data) |
__() |
Translate text | __('Welcome, %s', $name) |
__e() |
Translate and escape text | __e('Welcome, %s', $name) |
vite() |
Include Vite assets | vite()->asset('app.js') |
Authentication
Function | Description | Example |
---|---|---|
auth() |
Get auth instance | auth()->login($user) |
user() |
Get current user or property | user('email') |
is_guest() |
Check if user is guest | if (is_guest()) |
hashing() |
Get hash utility | hashing()->make($password) |
File System
Function | Description | Example |
---|---|---|
root_dir() |
Get application root path | root_dir('app/Models') |
storage_dir() |
Get storage path | storage_dir('logs') |
lang_dir() |
Get language files path | lang_dir('en') |
upload_dir() |
Get uploads path | upload_dir('images') |
Cache Utility
The Cache utility provides a simple yet powerful caching mechanism for storing and retrieving data with expiration support.
Cache Interface Methods
Method | Description | Example |
---|---|---|
has() |
Checks if a cache key exists | cache()->has('user_data') |
store() |
Stores data in cache with optional expiration | cache()->store('user_data', $data, '+1 hour') |
load() |
Gets or generates data if not cached | cache()->load('user_data', fn() => fetchData(), '+30 minutes') |
retrieve() |
Gets cached data | cache()->retrieve(['user_data', 'settings']) |
erase() |
Removes cached items | cache()->erase('user_data') |
flush() |
Clears entire cache | cache()->flush() |
Helper Functions
// Get or create cache instance
$cache = cache('user_cache');
// Store data with expiration
cache()->store('key', $data, '+1 day');
// Retrieve data (with callback if not exists)
$data = cache()->load('key', function() {
return expensiveOperation();
}, '+30 minutes');
// Remove cache instance
unload_cache('user_cache');
Expiration Formats
Expiration times can be specified as:
- Relative time:
'+1 hour'
,'+30 minutes'
- Absolute time:
'2023-12-31 23:59:59'
null
for no expiration
HTTP Utility
The HTTP utility provides a simple interface for making HTTP requests using cURL.
HTTP Interface Methods
Method | Description | Example |
---|---|---|
option() |
Sets cURL options | http()->option(CURLOPT_TIMEOUT, 30) |
header() |
Sets request headers | http()->header('Authorization', 'Bearer token') |
send() |
Makes HTTP request | http()->send('https://api.example.com', ['param' => 'value']) |
Helper Functions
// Simple GET request
$response = http('https://api.example.com');
// With parameters and headers
$response = http()
->header('Accept', 'application/json')
->send('https://api.example.com/users', ['page' => 2]);
// POST request example
$response = http()
->option(CURLOPT_POST, true)
->option(CURLOPT_POSTFIELDS, json_encode(['name' => 'John']))
->header('Content-Type', 'application/json')
->send('https://api.example.com/users');
Response Format
Requests return an array with these keys:
[
'body' => 'Response content',
'status' => 200,
'last_url' => 'Final URL after redirects',
'length' => 'Content length'
]
Common cURL Options
CURLOPT_TIMEOUT
- Request timeoutCURLOPT_FOLLOWLOCATION
- Follow redirectsCURLOPT_RETURNTRANSFER
- Return response as stringCURLOPT_SSL_VERIFYPEER
- Verify SSL certificate
Image Utility
The Image utility provides a simple interface for common image manipulation tasks including compression, resizing, and rotation.
Image Interface Methods
Method | Description | Example |
---|---|---|
compress() |
Compresses the image with specified quality | image('photo.jpg')->compress(80, 'compressed.jpg') |
resize() |
Resizes the image to exact dimensions | image('photo.jpg')->resize(800, 600) |
bulkResize() |
Creates multiple resized versions | image('photo.jpg')->bulkResize([300=>200, 800=>600]) |
rotate() |
Rotates the image by specified degrees | image('photo.jpg')->rotate(90) |
Helper Function
// Basic usage
$image = image('path/to/source.jpg');
// Chain operations
image('photo.jpg')
->resize(1200, 800)
->compress(85, 'optimized.jpg');
Compression Details
- For JPEG: Quality range 0-100 (higher is better quality)
- For PNG: Compression level 0-9 (higher is more compression)
- If no destination is provided, modifies the original image
Resizing Options
// Single resize
image('photo.jpg')->resize(800, 600, 'resized.jpg');
// Multiple sizes (returns array of generated files)
$resized = image('photo.jpg')->bulkResize([
300 => 200, // thumbnail
800 => 600, // medium
1200 => 900 // large
]);
Supported Image Formats
The utility supports common image formats including:
- JPEG/JPG
- PNG
bulkResize()
instead of
multiple resize()
calls as it's more memory efficient.
Mail Utility
The Mail utility provides a fluent interface for sending emails, supporting both plain text and HTML content, with options for templates, attachments, and multiple recipients.
Core Methods
Method | Description | Example |
---|---|---|
subject() |
Sets email subject | mailer()->subject('Welcome!') |
body() |
Sets plain text or HTML content | mailer()->body('Hello world', false) |
view() |
Sets content using template | mailer()->view('welcome', ['name'=>'John']) |
to() |
Adds recipient | mailer()->to('user@example.com', 'John') |
cc() |
Adds CC recipient | mailer()->cc('admin@example.com') |
bcc() |
Adds BCC recipient | mailer()->bcc('archive@example.com') |
mailer() |
Sets sender address | mailer()->mailer('noreply@example.com') |
reply() |
Sets reply-to address | mailer()->reply('support@example.com') |
send() |
Sends the email | mailer()->send() |
Helper Function
// Simple text email
mailer(
to: 'user@example.com',
subject: 'Welcome',
body: 'Thank you for registering',
isHtml: false
)->send();
// Template-based HTML email
mailer(
to: 'user@example.com',
subject: 'Your Order',
template: 'emails/order-confirmation',
context: ['order' => $order],
from: 'orders@example.com'
)->send();
// Fluent interface
mailer()
->to('user@example.com')
->subject('Reminder')
->view('emails/reminder', ['days' => 3])
->cc('manager@example.com')
->send();
Template Usage
Template files should be placed in your views directory (typically
resources/views/emails/
):
<!-- resources/views/emails/welcome.php -->
<h1>Welcome, <?= $name ?>!</h1>
<p>Thank you for joining our service.</p>
Configuration
Mail settings are configured in your environment file (env.php
):
// SMTP Configuration
'mail' => [
'mailer' => [
'address' => '{MAILER_ADDRESS}',
'name' => '{MAILER_NAME}'
],
'reply' => [
'address' => '{REPLY_ADDRESS}',
'name' => '{REPLY_NAME}'
],
'smtp' => [
'enabled' => false,
'host' => '{SMTP_HOST}',
'port' => 2525,
'username' => '{SMTP_USERNAME}',
'password' => '{SMTP_PASSWORD}',
'encryption' => 'tls|ssl',
],
],
Attachment Support
You can attach files to the email using the addAttachment()
method:
mailer()
->to('user@example.com')
->subject('Your Document')
->body('Please find attached document')
->addAttachment('/path/to/document.pdf')
->send();
Paginator Utility
The Paginator utility provides a complete solution for splitting data into pages and generating pagination links with customizable styling.
Basic Usage
// Initialize paginator with total items and per-page limit
$paginator = paginator(total: 150, limit: 15, data: $arrayOfData);
// In controller (with database query)
$paginator = DB::table('users')->paginate(15);
// In view
<?php foreach ($paginator->getData() as $user): ?>
<!-- Display user -->
<?php endforeach ?>
<?= $paginator->getLinks() ?>
Core Methods
Method | Description | Example |
---|---|---|
getData() |
Gets paginated data subset | $paginator->getData(true) |
getLinks() |
Generates pagination HTML | $paginator->getLinks(3) |
getPage() |
Gets current page number | $currentPage = $paginator->getPage() |
getPages() |
Gets total page count | $totalPages = $paginator->getPages() |
getOffset() |
Gets current offset | $offset = $paginator->getOffset() |
hasData() |
Checks if data exists | if ($paginator->hasData()) |
hasLinks() |
Checks if pagination needed | if ($paginator->hasLinks()) |
Customizing Pagination Links
// Custom CSS classes
$paginator->getLinks(2, [
'ul' => 'pagination-list',
'li' => 'pagination-item',
'a' => 'pagination-link',
'li.current' => 'is-active',
'a.current' => 'current-link'
]);
// Custom previous/next text
$paginator->getLinks(2, [], [
'prev' => '«',
'next' => '»'
]);
Database Integration
When working with databases, use the offset and limit for queries:
// In controller
$paginator = paginator(
total: DB::table('products')->count(),
limit: 20
);
$products = DB::table('products')
->offset($paginator->getOffset())
->limit($paginator->getLimit())
->get();
$paginator->setData($products);
// or simply use (RECOMMENDED)
$paginator = DB::table('products')->paginate(20);
Lazy Loading vs Eager Loading
// Eager loading (pre-sliced data)
$paginator->setData($fullArray)->getData(false);
// Lazy loading (auto-slices data)
$paginator->setData($fullArray)->getData(true);
URL Customization
Change the page parameter keyword:
// Initialize with custom parameter
$paginator = paginator(200, 10, 'pg');
// Will generate URLs like: /items?pg=2
File Uploader Utility
The Uploader utility provides a robust solution for handling file uploads with support for validation, automatic resizing, compression, and secure file naming.
Basic Usage
// Simple file upload
$uploader = uploader(uploadTo: 'products', extensions: ['jpg', 'png']);
$filePath = $uploader->upload('file_input_name');
// Multiple file upload with size limit
$uploader = uploader(
uploadTo: documents/25-March',
extensions: ['pdf', 'docx'],
maxSize: 5 * 1024 * 1024 // 5MB
);
$filePaths = $uploader->upload('multiple_files_input');
Core Methods
Method | Description | Example |
---|---|---|
setup() |
Configures upload settings | $uploader->setup('uploads', ['jpg'], false, 2048000) |
setUploadDir() |
Sets upload directory | $uploader->setUploadDir('new_uploads') |
upload() |
Processes file upload | $uploader->upload($_FILES['avatar']) |
Image Processing Features
// Single resize + compression
$uploader = uploader(
uploadDir: root_dir('uploads/products'),
extensions: ['jpg', 'png'],
resize: [800 => 600], // width => height
compress: 80 // quality percentage
);
$imagePath = $uploader->upload('product_image');
// Multiple resizes
$uploader = uploader(
uploadDir: root_dir('uploads/gallery'),
resizes: [
[300 => 200], // thumbnail
[800 => 600], // medium
[1200 => 900] // large
]
);
$imageVersions = $uploader->upload('gallery_photos'); // Returns array of paths
Security Features
- Automatic secure filename generation
- File extension validation
- File size limits
- Directory permission checks
- Automatic directory creation
Helper Function
// Using the uploader() helper
$uploader = uploader(
uploadTo: 'avatars',
extensions: ['jpg', 'jpeg', 'png'],
maxSize: 2 * 1024 * 1024, // 2MB
compress: 75
);
// Handle form submission
if (request()->hasFile('avatar')) {
try {
$avatarPath = $uploader->upload('avatar');
// Save path to database
} catch (UploaderUtilException $e) {
// Handle error
$error = $e->getMessage();
}
}
Configuration Options
Parameter | Description | Default |
---|---|---|
uploadDir |
Target directory for uploads | config('upload_dir') |
uploadTo |
Sub directory for uploads | null |
extensions |
Allowed file extensions | [] (all allowed) |
multiple |
Allow multiple files | null (auto-detect) |
maxSize |
Maximum file size in bytes | 2097152 (2MB) |
resize |
Single resize dimensions | null |
resizes |
Multiple resize dimensions | null |
compress |
Image quality (0-100) | null |
Error Handling
try {
$file = uploader('protected')->upload('document');
} catch (UploaderUtilException $e) {
// Handle specific error cases
switch ($e->getCode()) {
case 501:
// Failed to create upload directory.
break;
case 502:
// Upload directory is not writable.
break;
case 503:
// File size exceeds the maximum limit.
break;
case 504:
// Invalid file extension.
break;
default:
// Failed to move uploaded file.
break;
}
}
resizes
instead of
multiple separate uploads.
Support Classes
The framework includes powerful support classes inspired by Laravel's support components to make working with arrays, strings, and collections more expressive and convenient.
Collection Class
The Collection
class provides a fluent, convenient wrapper for working with arrays
of data.
Basic Usage
// Create collection
$collection = collect(['taylor', 'abigail', null])
->map(fn ($name) => strtoupper($name))
->reject(fn ($name) => empty($name));
// Chain methods
$collection->filter()->each()->map()->sort()
Common Methods
Method | Description | Laravel Docs |
---|---|---|
all() |
Get all items | Link |
map() |
Transform each item | Link |
filter() |
Filter items | Link |
groupBy() |
Group items by key | Link |
sortBy() |
Sort items | Link |
Helper Function
// Create collection from array
$collection = collect([1, 2, 3]);
Array Support (Arr)
The Arr
class provides helper methods for array manipulation.
Common Methods
Method | Description | Laravel Docs |
---|---|---|
Arr::get() |
Get item from array using dot notation | Link |
Arr::set() |
Set array item using dot notation | Link |
Arr::has() |
Check if item exists in array | Link |
Arr::pluck() |
Pluck values from array | Link |
Helper Functions
// Dot notation access
$value = data_get($array, 'user.address.street');
// Set nested value
data_set($array, 'user.address.street', '123 Main');
// Remove nested value
data_forget($array, 'user.address.street');
// Fill missing value
data_fill($array, 'user.role', 'guest');
String Support (Str & Stringable)
The Str
and Stringable
classes provide fluent string manipulation.
Common Methods
Method | Description | Laravel Docs |
---|---|---|
Str::after() |
Get string after first occurrence | Link |
Str::before() |
Get string before first occurrence | Link |
Str::contains() |
Check if string contains value | Link |
Str::finish() |
Ensure string ends with value | Link |
Str::limit() |
Limit string length | Link |
Fluent Strings
// Using Stringable
$string = str('Hello World')
->after('Hello')
->trim()
->append('!')
->upper();
// Using helper
$slug = str($title)->slug();
Other Support Classes
Number
use Spark\Support\Number;
Number::format(1000); // 1,000
Number::percentage(50); // 50%
Pluralizer
use Spark\Support\Pluralizer;
Pluralizer::plural('child'); // children
Pluralizer::singular('children'); // child
HtmlString
use Spark\Support\HtmlString;
new HtmlString('<h1>Safe HTML</h1>');
Js
use Spark\Support\Js;
Js::from($array); // JSON encoded with escaped characters
Support Helper Functions
Function | Description | Laravel Docs |
---|---|---|
head() |
Get first array element | Link |
last() |
Get last array element | Link |
value() |
Return value or call closure | Link |
when() |
Conditional execution | Link |
blank() |
Check if value is "blank" | Link |
filled() |
Check if value is not "blank" | Link |
class_basename() |
Get class name without namespace | Link |
tap() |
Tap into fluent chain | Link |
transform() |
Transform value if not blank | Link |
with() |
Return value after callback | Link |
Macroable Trait
The Macroable
trait allows you to add methods to classes at runtime.
// Add macro to Collection
Collection::macro('uppercase', function () {
return $this->map(fn ($item) => strtoupper($item));
});
// Use the macro
collect(['a', 'b'])->uppercase(); // ['A', 'B']