d

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.

15 St Margarets, NY 10033
(+381) 11 123 4567
ouroffice@aware.com

 

KMF

How to Use Laravel Macro With Example?

Macro is a powerful feature of the Laravel framework. Laravel Macros allow you to add custom functionality to internal Laravel components.

In this post, we will be looking at how we can use Laravel Macros and which classes can be used to define Macros.

If you see the Laravel codebase, you’ll find countless references to a trait called Macroable. This trait allows you to extend the public interface of a class in real-time.

Creating a Laravel Macro

Before creating a Laravel Macro, you have to make sure your targeted class use the Macroable trait. Here, we will be creating a Macro on the IlluminateSupportStr class, which will check the length of a given string named isLength. You can define the macro in your AppServiceProvider class’s boot() method.

Within the boot method of AppServiceProvider, we are defining a isLength macro on Str class which simply compare the length of first parameter with second one.

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

Laravel’s Macroable Classes

The following list are all of the Laravel classes that currently use the Macroable trait and accept macro calls.

  • IlluminateAuthRequestGuard
  • IlluminateAuthSessionGuard
  • IlluminateCacheRepository
  • IlluminateConsoleCommand
  • IlluminateConsoleSchedulingEvent
  • IlluminateCookieCookieJar
  • IlluminateDatabaseEloquentFactoryBuilder
  • IlluminateDatabaseEloquentRelationsRelation
  • IlluminateDatabaseGrammar
  • IlluminateDatabaseQueryBuilder
  • IlluminateDatabaseSchemaBlueprint
  • IlluminateFilesystemFilesystem
  • IlluminateFoundationTestingTestResponse
  • IlluminateHttpJsonResponse
  • IlluminateHttpRedirectResponse
  • IlluminateHttpRequest
  • IlluminateHttpResponse
  • IlluminateHttpUploadedFile
  • IlluminateMailMailer
  • IlluminateRoutingPendingResourceRegistration
  • IlluminateRoutingRedirector
  • IlluminateRoutingResponseFactory
  • IlluminateRoutingRoute
  • IlluminateRoutingRouter
  • IlluminateRoutingUrlGenerator
  • IlluminateSupportArr
  • IlluminateSupportCollection
  • IlluminateSupportLazyCollection
  • IlluminateSupportStr
  • IlluminateSupportTestingFakesNotificationFake
  • IlluminateTranslationTranslator
  • IlluminateValidationRule
  • IlluminateViewFactory
  • IlluminateViewView

Credit: Source link

Previous Next
Close
Test Caption
Test Description goes like this