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);
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.