Unlocking the Power of Macros in Laravel

Sandeeppant
2 min readMar 16, 2025

In Laravel, macros allow you to extend built-in classes with custom methods dynamically. This feature is useful when you want to add reusable functionality to Laravel components like collections, routes, request, string helpers, etc., without modifying their core files.

For Example

use Illuminate\Support\Collection;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{

public function boot(): void
{
// Defined a macro 'paginate' on the Collection class
Collection::macro('paginate', function ($perPage = 15, $page = null, $options = []) {
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);

return new LengthAwarePaginator(
$this->forPage($page, $perPage)->values(),
$this->count(),
$perPage,
$page,
$options
);
});
}

}

// Example usage of the custom pagination macro
$posts = collect([
// Sample data
['id' => 1, 'title' => 'PHP'],
// ... more sample data ...
['id' => 10, 'title' => 'Go'],
]);

$paginatedPosts = $posts->paginate(5);

// Displaying the paginated results
echo "With Macro:\n";
foreach ($paginatedPosts as $post) {
echo $post['title'] . "\n";
}
// Example without the custom macro
// Manually slicing the collection for pagination
$page = 1;
$perPage = 5;
$offset = ($page - 1) * $perPage;
$paginatedPostsManual = new LengthAwarePaginator(
$posts->slice($offset, $perPage)->values(),
$posts->count(),
$perPage,
$page,
['path' => Paginator::resolveCurrentPath()]
);

echo "\nWithout Macro:\n";
foreach ($paginatedPostsManual as $post) {
echo $post['title'] . "\n";
}
  • The custom paginate macro simplifies pagination by encapsulating logic within a reusable method.
  • The comparison between using the macro and manual pagination techniques highlights the macro’s convenience and readability.

This above examples not only showcases a custom pagination macro for Laravel collections but also compares its usage with standard collection operations.

Sign up to discover human stories that deepen your understanding of the world.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response