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.
File Manager Utility
The File Manager utility provides comprehensive file and directory operations with support for file manipulation, directory management, and various file system operations.
Basic Usage
// Using helper functions
$fm = filemanager(); // or fm()
// Check if file exists
if (fm()->exists('/path/to/file.txt')) {
$content = fm()->get('/path/to/file.txt');
}
// Create directory recursively
fm()->ensureDirectoryExists('/path/to/new/directory', 0755);
// Get all files in directory
$files = fm()->files('/path/to/directory');
Core Methods
Method | Description | Example |
---|---|---|
exists() |
Check if file/directory exists | fm()->exists('/path/file.txt') |
get() |
Get file contents | fm()->get('/path/file.txt') |
put() |
Write content to file | fm()->put('/path/file.txt', 'content') |
delete() |
Delete file(s) | fm()->delete('/path/file.txt') |
makeDirectory() |
Create directory | fm()->makeDirectory('/path/dir') |
files() |
Get files in directory | fm()->files('/path/dir') |
allFiles() |
Get all files recursively | fm()->allFiles('/path/dir') |
File Operations
// Read and write files
$content = fm()->get('/path/file.txt');
fm()->put('/path/new.txt', $content);
// Append to file
fm()->append('/path/log.txt', "New log entry\n");
// Prepend to file
fm()->prepend('/path/log.txt', "First entry\n");
// Move and copy files
fm()->move('/old/path.txt', '/new/path.txt');
fm()->copy('/source.txt', '/backup.txt');
// Get file information
$size = fm()->size('/path/file.txt');
$mime = fm()->mimeType('/path/image.jpg');
$modified = fm()->lastModified('/path/file.txt');
Directory Operations
// Create directories
fm()->makeDirectory('/path/to/dir', 0755, true);
// Ensure directory exists and is writable
fm()->ensureDirectoryWritable('/path/to/uploads');
// List directory contents
$files = fm()->files('/path/dir');
$directories = fm()->directories('/path/dir');
// Recursive directory operations
$allFiles = fm()->allFiles('/path/dir');
fm()->copyDirectory('/source', '/destination');
fm()->deleteDirectory('/path/to/delete');
// Clean directory (remove contents but keep directory)
fm()->cleanDirectory('/path/to/clean');
Advanced Features
// File hashing and comparison
$hash = fm()->hash('/path/file.txt', 'sha256');
$same = fm()->same('/file1.txt', '/file2.txt');
// Atomic file writes (prevents partial writes)
fm()->putAtomic('/path/file.txt', 'important data');
// Generate unique filenames
$uniqueName = fm()->uniqueFilename('/uploads', 'image.jpg');
// Get human-readable file size
$size = fm()->humanFileSize(1024 * 1024); // Returns "1.00 MB"
// Symbolic links (cross-platform)
fm()->link('/target/file', '/link/path');
// File permissions
$perms = fm()->permissions('/path/file.txt');
fm()->chmod('/path/file.txt', 0644);
Helper Functions
// Using the filemanager() and fm() helpers
if (filemanager()->exists($filePath)) {
$content = fm()->get($filePath);
}
// Common usage pattern
public function storeFile($uploadedFile)
{
$uploadDir = '/uploads/' . date('Y-m');
fm()->ensureDirectoryWritable($uploadDir);
$filename = fm()->uniqueFilename($uploadDir, $uploadedFile['name']);
$filePath = $uploadDir . '/' . $filename;
if (fm()->put($filePath, file_get_contents($uploadedFile['tmp_name']))) {
return $filePath;
}
return false;
}
Security Features
- Secure file permission management
- Directory traversal prevention
- Atomic file operations
- File integrity checking through hashing
- Safe directory creation with proper permissions
ensureDirectoryWritable()
to safely manage upload directories.
allFiles()
cautiously on large directories as
it recursively scans all subdirectories.
Carbon Time Utility
The Carbon Time utility provides a comprehensive DateTime manipulation library with intuitive API for date and time operations, formatting, and calculations.
Basic Usage
// Using helper functions
$now = now(); // Current datetime
$specific = carbon('2023-12-25 15:30:00');
// Create from various formats
$fromTimestamp = carbon(1671980400);
$fromFormat = Carbon::createFromFormat('d/m/Y', '25/12/2023');
// Basic formatting
echo $now->toDateTimeString(); // 2023-12-25 10:30:45
echo $now->toDateString(); // 2023-12-25
echo $now->toTimeString(); // 10:30:45
Core Methods
Method | Description | Example |
---|---|---|
now() |
Current datetime | $now = now() |
carbon() |
Create from string/timestamp | carbon('2023-12-25') |
today() |
Today at midnight | Carbon::today() |
yesterday() |
Yesterday at midnight | Carbon::yesterday() |
tomorrow() |
Tomorrow at midnight | Carbon::tomorrow() |
format() |
Custom formatting | $now->format('Y-m-d H:i:s') |
Date Manipulation
// Adding time
$future = now()->addDays(7)->addHours(3);
$nextMonth = now()->addMonths(1);
$nextYear = now()->addYears(1);
// Subtracting time
$past = now()->subDays(5)->subMinutes(30);
$lastMonth = now()->subMonths(1);
// Start/end of periods
$startOfDay = now()->startOfDay();
$endOfDay = now()->endOfDay();
$startOfWeek = now()->startOfWeek();
$endOfWeek = now()->endOfWeek();
$startOfMonth = now()->startOfMonth();
$endOfMonth = now()->endOfMonth();
$startOfYear = now()->startOfYear();
$endOfYear = now()->endOfYear();
Date Comparison
// Date comparisons
$date1 = carbon('2023-12-25');
$date2 = carbon('2023-12-31');
$date1->isAfter($date2); // false
$date1->isBefore($date2); // true
$date1->equals($date2); // false
$date1->isSameDay($date2); // false
// Relative checks
$date->isToday(); // true if today
$date->isTomorrow(); // true if tomorrow
$date->isYesterday(); // true if yesterday
$date->isFuture(); // true if in future
$date->isPast(); // true if in past
$date->isWeekend(); // true if weekend
$date->isWeekday(); // true if weekday
Difference Calculations
// Time differences
$diffSeconds = $date1->diffInSeconds($date2);
$diffMinutes = $date1->diffInMinutes($date2);
$diffHours = $date1->diffInHours($date2);
$diffDays = $date1->diffInDays($date2);
// Human-readable differences
echo $date1->diffForHumans($date2); // "6 days ago" or "in 6 days"
// Age calculation
$birthday = carbon('1990-05-15');
$age = $birthday->age(); // 33 (current age)
Timezone Handling
// Setting default timezone
Carbon::setDefaultTimezone('Europe/London');
// Working with timezones
$utcTime = now()->setTimezone('UTC');
$newYorkTime = now()->setTimezone('America/New_York');
// Get timezone information
$timezone = now()->getTimezone();
echo $timezone->getName(); // Europe/London
Helper Functions
// Using the now() and carbon() helpers
$current = now();
$specific = carbon('2023-12-25 15:30:00');
// Common usage patterns
public function isEventActive($eventDate)
{
$event = carbon($eventDate);
return $event->isFuture() && $event->isWeekday();
}
public function formatEventDate($eventDate)
{
return carbon($eventDate)->toFormattedDateString(); // Dec 25, 2023
}
public function getDaysUntilEvent($eventDate)
{
return now()->diffInDays(carbon($eventDate));
}
Advanced Features
// Working with arrays
$dateArray = now()->toArray();
/*
[
'year' => 2023,
'month' => 12,
'day' => 25,
'hour' => 10,
'minute' => 30,
'second' => 45,
...
]
*/
// Finding min/max dates
$dates = [
carbon('2023-12-25'),
carbon('2023-12-31'),
carbon('2024-01-01')
];
$earliest = Carbon::minDate(...$dates);
$latest = Carbon::maxDate(...$dates);
// Cloning and modification
$original = now();
$modified = $original->clone()->addDay();
// $original remains unchanged
Configuration
// Set application-wide default timezone
Carbon::setDefaultTimezone('Asia/Dhaka');
// The timezone can be a string or DateTimeZone object
Carbon::setDefaultTimezone(new DateTimeZone('UTC'));
// All new instances will use this timezone
$utcTime = now(); // Uses UTC timezone
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']