<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by mritunjay khichi on Medium]]></title>
        <description><![CDATA[Stories by mritunjay khichi on Medium]]></description>
        <link>https://medium.com/@algomsk?source=rss-4d87e717a0a7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bCmUeqbjB9IoBo3CoG4myw.png</url>
            <title>Stories by mritunjay khichi on Medium</title>
            <link>https://medium.com/@algomsk?source=rss-4d87e717a0a7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:46:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@algomsk/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Unleashing the Magic of Laravel Macros]]></title>
            <link>https://medium.com/simform-engineering/unleashing-the-magic-of-laravel-macros-c079ebee11cc?source=rss-4d87e717a0a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c079ebee11cc</guid>
            <category><![CDATA[eloquent-orm]]></category>
            <category><![CDATA[collection]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[macro]]></category>
            <dc:creator><![CDATA[mritunjay khichi]]></dc:creator>
            <pubDate>Fri, 28 Jul 2023 06:14:03 GMT</pubDate>
            <atom:updated>2023-07-28T06:14:03.234Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Enhancing Laravel: Harnessing the Power of Macros. Elevate your code with Custom Functionalities.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lDCi2MHBMxPVjPTMsDCHPQ.png" /></figure><p>In the mystical realm of web development, Laravel stands as a powerful PHP framework. Within the framework, there’s a hidden secret called “Laravel Macros.” These are like magical incantations that empower developers to add custom abilities to their code, without changing its main structure. In easy terms, a Laravel Macro is a technique that allows us to add new functionalities to Laravel’s internal components using custom code that is not originally part of the Laravel class. To achieve this, Laravel offers a PHP trait called Macroable. With a practical code example as our guide, we’ll explore the full potential of Laravel Macros in this post.</p><h3>Getting Started</h3><p>Let’s begin with how to create Macros, and then, we’ll delve into how to use them the right way.</p><h4><strong>Creating a Macro</strong></h4><p>We need to create a Laravel Macro, which is like forging a powerful blade. But before that, we require a service provider.</p><pre>php artisan make:provider MagicalMacroServiceProvider</pre><p>Within this newfound provider, we shall wield our powers:</p><pre>use Illuminate\Support\ServiceProvider;<br><br>class MagicalMacroServiceProvider extends ServiceProvider<br>{<br>    public function boot()<br>    {<br>        // Eloquent model macros<br>        \App\Models\User::macro(&#39;greet&#39;, function () {<br>            return &#39;Greetings, dear &#39; . $this-&gt;name . &#39;!&#39;;<br>        });<br><br>        // Collection macros<br>        \Illuminate\Support\Collection::macro(&#39;addOne&#39;, function () {<br>            return $this-&gt;map(function ($item) {<br>                return $item + 1;<br>            });<br>        });<br>    }<br><br>    public function register()<br>    {<br>        //<br>    }<br>}</pre><h4><strong>Using Our Macros</strong></h4><p>Now that we’ve created the Macros and activated our service provider, we are prepared to use its power. Watch as the simple User model transforms into something more impressive:</p><pre>$user = \App\Models\User::find(1);<br>echo $user-&gt;greet(); // Output: &quot;Greetings, dear [User Name]!&quot;</pre><p>But that’s not all; our Collection now possesses the power to augment:</p><pre>$numbers = collect([1, 2, 3, 4, 5]);<br>$augmentedNumbers = $numbers-&gt;addOne();<br>// Output: [2, 3, 4, 5, 6]</pre><h3><strong>Best Practices and Precautions</strong></h3><p>Macros are a potent tool, but with great power comes great responsibility. Follow these precautions to ensure the safety of your codebase:</p><ul><li>Document your Macros: Record the purpose, parameters, and expected outcomes of each Macro to aid fellow developers and future travelers.</li><li>Avoid Macro Name Clashes: Be cautious not to overwrite existing methods, and prefix your Macro names uniquely to prevent conflicts.</li><li>Limit the Scope: Define Macros within service providers that load only when required rather than global providers.</li></ul><p>You can define Macros on any class that uses the Macroable trait. Here’s a list of classes and facades that are Macroable:</p><p><strong>Facades</strong></p><ul><li>Cache</li><li>File</li><li>Lang</li><li>Request</li><li>Response</li><li>Route</li><li>URL</li></ul><p><strong>Illuminate Classes</strong></p><ul><li>Illuminate\Cache\Repository</li><li>Illuminate\Console\Scheduling\Event</li><li>Illuminate\Database\Eloquent\Builder</li><li>Illuminate\Database\Eloquent\Relation</li><li>Illuminate\Database\Query\Builder</li><li>Illuminate\Filesystem\Filesystem</li><li>Illuminate\Foundation\Testing\TestResponse</li><li>Illuminate\Http\RedirectResponse</li><li>Illuminate\Http\Request</li><li>Illuminate\Http\UploadedFile</li><li>Illuminate\Routing\ResponseFactory</li><li>Illuminate\Routing\Router</li><li>Illuminate\Routing\UrlGenerator</li><li>Illuminate\Support\Arr</li><li>Illuminate\Support\Collection</li><li>Illuminate\Support\Str</li><li>Illuminate\Translation\Translator</li><li>Illuminate\Validation\Rule</li></ul><h3><strong>Real-World Problem</strong></h3><h4><strong>Improving Online Product Recommendations</strong></h4><p>Let’s consider a real-world problem faced by an e-commerce platform that wants to enhance its product recommendation system to provide more personalized and accurate suggestions to its users. The current recommendation system is generic and does not take into account each user’s preferences, leading to suboptimal user experiences and lower conversion rates.</p><h4><strong>Solution using Laravel Macros</strong></h4><p>To address this issue, we can utilize Laravel Macros to extend the functionality of the existing Eloquent models and collections, enabling the platform to deliver more tailored and relevant product recommendations to its users based on their past interactions and preferences.</p><p><em>Step 1: Database Setup and Model Creation</em></p><p>First, we need to set up the database and create an Eloquent model for the “User” and “Product” tables.</p><p><em>Step 2: Defining Eloquent Model Macros</em></p><p>In our MacroServiceProvider, we can define Eloquent model macros that will be used to fetch personalized product recommendations for each user. These macros will encapsulate the logic for retrieving relevant product suggestions based on user interactions.</p><pre>use App\Models\User;<br>use App\Models\Product;<br><br>class MacroServiceProvider extends ServiceProvider<br>{<br>    public function boot()<br>    {<br>        // Eloquent model macros<br>        User::macro(&#39;personalizedRecommendations&#39;, function () {<br>            // Fetch products based on user interactions (e.g., viewed, purchased, etc.)<br>            return Product::whereIn(&#39;id&#39;, $this-&gt;viewedProducts()-&gt;pluck(&#39;id&#39;))<br>                -&gt;orWhereIn(&#39;id&#39;, $this-&gt;purchasedProducts()-&gt;pluck(&#39;id&#39;))<br>                -&gt;get();<br>        });<br>    }<br><br>    // Rest of the service provider code...<br>}</pre><p><em>Step 3: Retrieving Personalized Recommendations</em></p><p>With the personalizedRecommendations macro defined, we can now use it to retrieve personalized product recommendations for each user.</p><pre>// Assume we have an authenticated user<br>$user = Auth::user();<br><br>// Get personalized product recommendations for the user<br>$recommendations = $user-&gt;personalizedRecommendations();</pre><p>The personalizedRecommendations the macro will leverage the viewedProducts() and purchasedProducts() methods (which should also be defined in the User model) to determine which products the user has interacted with in the past. It will then use this information to fetch relevant product recommendations, based on their preferences and past actions.</p><h3>Key takeaway</h3><p>Laravel Macros are a developer’s secret weapon to elevate their code and make it truly exceptional. Just like casting a magical spell, Macros allow you to add custom powers to your Laravel classes. They make your code more efficient, reusable, and maintainable. Embrace the magic of Laravel Macros, and watch your code transform into something extraordinary.</p><blockquote><strong>To stay up-to-date with the latest trends in the development ecosystem, follow</strong><a href="https://medium.com/simform-engineering"><strong> Simform Engineering</strong></a><strong>.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c079ebee11cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/simform-engineering/unleashing-the-magic-of-laravel-macros-c079ebee11cc">Unleashing the Magic of Laravel Macros</a> was originally published in <a href="https://medium.com/simform-engineering">Simform Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>