How to Create and uses Laravel Macro Example Tutorial?

10-Apr-2023

.

Admin

How to Create and uses Laravel Macro Example Tutorial?

Hello Friends,

In this tutorial, you will learn how to create and uses the laravel macro example tutorial. I would like to share with you how to use macros in the laravel app. it's a simple example of how to use laravel macro with an example. This article will give a simple example of how to create response macros in laravel. Follow the tutorial below on how to develop and use the laravel macro example.

Macro is a powerful feature of the laravel framework. Macros allow you to add custom functionality to internal Laravel components like a response:: macro, laravel macroable, etc. This laravel macro also works with laravel apps.

You can use this example with the versions of laravel 6, laravel 7, laravel 8, and laravel 9.

You have just to follow the below step and you will get the layout as below:

Step 1: Install Laravel


This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Creating a Laravel Macro

Here, we will be creating a Macro on the Illuminate\Support\Str class, which will check the length of a given string named isLength. You can define the macro in your AppServiceProvider class’s boot() method

app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Illuminate\Support\Str;

class AppServiceProvider extends ServiceProvider

{

/**

* Register any application services.

*

* @return void

*/

public function register()

{

//

}

/**

* Bootstrap any application services.

*

* @return void

*/

public function boot()

{

Str::macro('isLength', function ($str, $length) {

return static::length($str) == $length ? 'string length is '.$length : 'string length is not '.$length;

});

}

}

Test Macro

Now, you can use this Macro anywhere in your application.

web.php

<?php

use Illuminate\Support\Facades\Route;

use Illuminate\Support\Str;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

Route::get('/', function () {

dd(Str::isLength('This is a Laravel Macro', 24));

return view('welcome');

});

Start the development server. Use the PHP artisan serve command and start your server:

php artisan serve

Now you are ready to run our example so run the below command to quick run.

http://localhost:8000

Output:

string length is not 24

I hope it can help you...

#Laravel