Laravel 10 How To Create Macro with Examples Tutorial

Reading Time: 5 minutes
235 Views

Laravel, a strong PHP framework, provides developers with a wide range of features and tools for effectively building online applications. The ability to build macros, which lets you to add custom functionality to various Laravel components and classes, is one of its extensibility capabilities.

Laravel Macros are a great way of extending Laravel’s core classes and add extra functionality as required for application.

In this tutorial, we will walk you through the process of developing macros in Laravel 10 with real examples, allowing you to enhance Laravel’s basic functionality to meet the specific demands of your application.

Read More: Laravel 10 How To Redirect with Form Inputs Tutorial

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

What is Macro in Laravel?

A “macro” in Laravel refers to the ability to add additional methods or features to various classes or framework components without altering the original source code.

Laravel’s macro feature enables developers to enhance the capabilities of fundamental Laravel classes such as Eloquent models, collections, query builders, and others.

This is how Laravel macros operate and why they are useful:

  • Extensibility: Laravel macros allow developers to add additional methods to existing Laravel classes, making it easy to expand and customise the basic functionality of Laravel.
  • Clean and Organized: Macros help to keep your codebase clean and organised. You can wrap custom functionality into macros rather than changing the core Laravel code or writing helper functions.
  • Reusability: Macros, once developed, can be utilised across your application, boosting code reuse. This is especially handy when you wish to apply common operations or behaviours consistently.
  • Expression: By enclosing difficult or repetitive logic into named methods, macros make your code more expressive and readable.

How To Create a Laravel Macro?

Before creating a Laravel Macro, you have to make sure that your targeted class use the Macroable trait.

Register a Macro,

Open AppServiceProvider.php from /app/Providers folder. Add macro using boot() method of it,

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Str::macro('checkLength', function ($str, $length) {
           
            return static::length($str) == $length ? 'String Length is ' . $length : 'String length is not ' . $length;
        });

        Str::macro('truncateText', function ($value, $length, $append = '...') {
            return Str::limit($value, $length, $append);
        });
    }
}

Read More: Laravel 10 How To Integrate Ckeditor Plugin Tutorial

Here, in the given example Targeted class is Str. Now, you have two macros checkLength and truncateText.

Create Route

Open web.php file from /routes folder. Add these routes into it.

//...

use Illuminate\Support\Str;

Route::get('route-1', function () {

    // Use the checkLength macro
    $text = 'This is a long text that needs truncating.';
    $data = Str::checkLength($text, 56);

    echo $data;
  
});

Route::get('route-2', function () {

   // Use the truncateText macro
   $text = 'This is a long text that needs truncating.';
   $shortened = Str::truncateText($text, 20);

   echo $shortened;
  
});

//...

Application Testing

Run this command into project terminal to start development server,

php artisan serve

URL: http://127.0.0.1:8000/route-1

Output

String length is not 56

URL: http://127.0.0.1:8000/route-2

Output

This is a long text...

That’s it.

We hope this article helped you to learn about Laravel 10 How To Create Macro with Examples Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more