Join WhatsApp ChannelJoin Now

Laravel Macro Methods

अगर आप Laravel developer हैं, तो आप ने Service Providers, Facades, और Helper functions तो जरूर use किए होंगे। लेकिन क्या आपने कभी Laravel Macros के बारे में सुना है?

Macro एक कम-ज्ञात लेकिन बहुत powerful फीचर है जो आपको Laravel की existing core classes जैसे Str, Collection, Request वगैरह में custom methods जोड़ने की सुविधा देता है — बिना core को override किए।

Laravel Macro क्या होता है?

Macro का मतलब है: “किसी existing class में नई method जोड़ना।” यानी आप Laravel के core component जैसे Str या Collection को enhance कर सकते हैं custom methods से — वो भी globally पूरे app में।

उदाहरण के लिए, अगर आप बार-बार product name से slug बनाते हैं, तो उसके लिए आप एक macro method बना सकते हैं:

// AppServiceProvider.php के boot() method में डालें
use Illuminate\Support\Str;

public function boot()
{
    Str::macro('productSlug', function ($name) {
        return Str::slug($name) . '-' . rand(1000, 9999);
    });
}

अब आप Laravel app में कहीं भी use कर सकते हैं:

$slug = Str::productSlug('Silver Payal');
// Output: silver-payal-3842

Collection में Macro कैसे जोड़ते हैं?

Collection class में आप custom methods ऐसे add कर सकते हैं:

use Illuminate\Support\Collection;

Collection::macro('toUpper', function () {
    return $this->map(function ($value) {
        return strtoupper($value);
    });
});

// Usage:
collect(['laravel', 'macro'])->toUpper();
// Output: ['LARAVEL', 'MACRO']

यह method automatically सभी collections में available हो जाएगी।

Request Macro का Example

कई बार आपको check करना होता है कि request api/ path से आ रही है या नहीं। उसके लिए:

use Illuminate\Http\Request;

Request::macro('isApiRequest', function () {
    return str_starts_with($this->path(), 'api/');
});

अब आप किसी भी controller या middleware में लिख सकते हैं:

if (request()->isApiRequest()) {
    // Do something for API
}

Macro के फायदे (Why Use Macros?)

  • Reusability: बार-बार लिखने वाली logic को centralize करो
  • Clean Code: helper functions से ज़्यादा readable और structured
  • Extend Laravel Core: Laravel की inbuilt classes को customize करो बिना hack किए

Recommended Posts