<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Dharmik Bhadkoliya</title>
    <description>The latest articles on DEV Community by Dharmik Bhadkoliya (@dharmik225).</description>
    <link>https://dev.to/dharmik225</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1224364%2F5e3f0868-4256-4409-be1c-99fd2a9a7459.jpeg</url>
      <title>DEV Community: Dharmik Bhadkoliya</title>
      <link>https://dev.to/dharmik225</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/dharmik225"/>
    <language>en</language>
    <item>
      <title>The State Pattern in Laravel: Like a Magician for Your App’s Logic</title>
      <dc:creator>Dharmik Bhadkoliya</dc:creator>
      <pubDate>Tue, 04 Feb 2025 04:19:59 +0000</pubDate>
      <link>https://dev.to/dharmik225/the-state-pattern-in-laravel-like-a-magician-for-your-apps-logic-3jmo</link>
      <guid>https://dev.to/dharmik225/the-state-pattern-in-laravel-like-a-magician-for-your-apps-logic-3jmo</guid>
      <description>&lt;p&gt;Hey there!&lt;br&gt;
Let’s talk about something magical that can make your Laravel projects cleaner, easier to understand, and a lot more fun to work with the state pattern. Don’t worry if you’re not familiar with it yet, I will explain everything using a simple and relatable example.&lt;/p&gt;
&lt;h2&gt;
  
  
  Why the State Pattern is Awesome
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Clean Code:&lt;/strong&gt; No more messy if-else blocks. Each state has its own class and handles its own logic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Easy to Add States:&lt;/strong&gt; Need a new state? Just create a new class. No need to touch existing code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Safe Transitions:&lt;/strong&gt; You can’t accidentally do something invalid, like shipping a pending order.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Readable and Fun:&lt;/strong&gt; The code is easier to read, understand, and maintain.&lt;/p&gt;
&lt;h2&gt;
  
  
  Why Use the State Pattern?
&lt;/h2&gt;

&lt;p&gt;Imagine you’re building a shopping app. Orders can go through several stages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Pending :&lt;/strong&gt; The order is created but not confirmed yet.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Confirmed :&lt;/strong&gt; The order is confirmed and ready to be packed.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Shipped :&lt;/strong&gt; The order is on its way to the customer.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Delivered :&lt;/strong&gt; The order has been delivered.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each of these states has its own rules. For example, you can’t ship an order that’s still pending, and you can’t deliver an order that hasn’t been shipped. Writing this logic with a bunch of &lt;code&gt;if-else&lt;/code&gt; or &lt;code&gt;switch&lt;/code&gt; statements can get really messy, really fast. That’s where the state pattern comes in to save the day!&lt;br&gt;
The state pattern helps us organize this logic by creating separate classes for each state. It’s like giving each state its own little brain to handle what it can and cannot do. Cool, right?&lt;/p&gt;
&lt;h2&gt;
  
  
  The Order States: Breaking It Down
&lt;/h2&gt;

&lt;p&gt;Let’s say our order can do three things:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Confirm :&lt;/strong&gt; Move the order to the "Confirmed" state.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Ship :&lt;/strong&gt; Move the order to the "Shipped" state.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Deliver :&lt;/strong&gt; Move the order to the "Delivered" state.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We’ll create a system where each state knows what actions it can perform. Ready? Let’s build it!&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 1: Create the State Interface
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;OrderStateInterface&lt;/code&gt; is like a rulebook for all order states. It makes sure every state knows what to do when you confirm, ship, or deliver an order. You'll find this interface in &lt;code&gt;App/States/Order/OrderStateInterface.php&lt;/code&gt;, and it keeps things organized by requiring each state to follow the same set of rules.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\States\Order;
interface OrderStateInterface
{
    public function confirm(): void;
    public function ship(): void;
    public function deliver(): void;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 2: The Base State Class
&lt;/h2&gt;

&lt;p&gt;We’ll make a base class for all states. If a state doesn’t support an action, it will throw an error.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\States\Order;
use App\Models\Order;
use Exception;

abstract class OrderState implements OrderStateInterface
{
    public function __construct(protected Order $order)
    {
    }

    public function confirm(): void
    {
        throw new Exception("You can’t confirm this order right now!");
    }

    public function ship(): void
    {
        throw new Exception("You can’t ship this order right now!");
    }

    public function deliver(): void
    {
        throw new Exception("You can’t deliver this order right now!");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 3: Create the Concrete States
&lt;/h2&gt;

&lt;h4&gt;
  
  
  Pending State
&lt;/h4&gt;

&lt;p&gt;The order is still pending and can only be confirmed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\States\Order;
class PendingState extends OrderState
{
    public function confirm(): void
    {
        $this-&amp;gt;order-&amp;gt;update(['status' =&amp;gt; 'confirmed']);
        $this-&amp;gt;order-&amp;gt;state = new ConfirmedState($this-&amp;gt;order);
        // Handle notifications, emails, etc.
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Confirmed State
&lt;/h4&gt;

&lt;p&gt;The order has been confirmed and can now be shipped.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\States\Order;
class ConfirmedState extends OrderState
{
    public function ship(): void
    {
        $this-&amp;gt;order-&amp;gt;update(['status' =&amp;gt; 'shipped']);
        $this-&amp;gt;order-&amp;gt;state = new ShippedState($this-&amp;gt;order);
        // Handle notifications, emails, etc.
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Shipped State
&lt;/h4&gt;

&lt;p&gt;The order is on its way and can now be delivered.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\States\Order;
class ShippedState extends OrderState
{
    public function deliver(): void
    {
        $this-&amp;gt;order-&amp;gt;update(['status' =&amp;gt; 'delivered']);
        $this-&amp;gt;order-&amp;gt;state = new DeliveredState($this-&amp;gt;order);
        // Handle notifications, emails, etc.
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Delivered State
&lt;/h4&gt;

&lt;p&gt;The order has been delivered. Nothing more can be done.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\States\Order;

class DeliveredState extends OrderState
{
    // No actions allowed here.
    // Handle notifications, emails, etc.
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 4: Update the Order Model
&lt;/h2&gt;

&lt;p&gt;The order model will figure out what state it’s in and behave accordingly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\Models;

use App\States\Order\{OrderStateInterface, PendingState, ConfirmedState, ShippedState, DeliveredState};

class Order extends Model
{
    protected $fillable = ['status'];

    public function orderState(): OrderStateInterface
    {
        return match ($this-&amp;gt;status) {
            'pending' =&amp;gt; new PendingState($this),
            'confirmed' =&amp;gt; new ConfirmedState($this),
            'shipped' =&amp;gt; new ShippedState($this),
            'delivered' =&amp;gt; new DeliveredState($this),
            default =&amp;gt; throw new \Exception("Unknown state"),
        };
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 5: Using It in a Controller
&lt;/h2&gt;

&lt;p&gt;Here I am taking different methods to use states for examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Order;
use App\States\Order\PendingState;
use Exception;

class OrderController extends Controller
{
    public function confirm(Order $order)
    {
        try {
            if ($order-&amp;gt;orderState() instanceof PendingState) {
                $order-&amp;gt;orderState()-&amp;gt;confirm();
                return redirect()-&amp;gt;route('orders.index')-&amp;gt;with('success', "Order #{$order-&amp;gt;id} has been confirmed.");
            }

            return redirect()-&amp;gt;route('orders.index')-&amp;gt;with('error', "Order #{$order-&amp;gt;id} cannot be confirmed in its current state.");
        } catch (Exception $e) {
            return redirect()-&amp;gt;route('orders.index')-&amp;gt;with('error', $e-&amp;gt;getMessage());
        }
    }

    public function updateState(Order $order, string $action)
    {
        try {
            if (!method_exists($order-&amp;gt;orderState(), $action)) {
                return redirect()-&amp;gt;route('orders.index')-&amp;gt;with('error', "Invalid action: {$action} for Order #{$order-&amp;gt;id}.");
            }

            $order-&amp;gt;orderState()-&amp;gt;$action();
            return redirect()-&amp;gt;route('orders.index')-&amp;gt;with('success', "Order #{$order-&amp;gt;id} has been updated successfully.");
        } catch (Exception $e) {
            return redirect()-&amp;gt;route('orders.index')-&amp;gt;with('error', $e-&amp;gt;getMessage());
        }
    }

    public function ship(Order $order)
    {
        return $this-&amp;gt;updateState($order, 'ship');
    }

    public function deliver(Order $order)
    {
        return $this-&amp;gt;updateState($order, 'deliver');
    }

    public function index()
    {
        return view('welcome');
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;The state pattern is a powerful way to manage application logic, making your Laravel app cleaner, more maintainable, and scalable. By organizing state-dependent behaviors into separate classes, you eliminate messy conditionals and improve readability. Implementing this approach in your projects will ensure a better development experience and fewer bugs. Try it out in your next Laravel project and see the magic happen!&lt;/p&gt;

</description>
      <category>php</category>
      <category>laravel</category>
    </item>
    <item>
      <title>Laravel Observers: The Silent Ninjas of Your Application Lifecycle</title>
      <dc:creator>Dharmik Bhadkoliya</dc:creator>
      <pubDate>Wed, 06 Nov 2024 12:46:06 +0000</pubDate>
      <link>https://dev.to/dharmik225/laravel-observers-the-silent-ninjas-of-your-application-lifecycle-2of8</link>
      <guid>https://dev.to/dharmik225/laravel-observers-the-silent-ninjas-of-your-application-lifecycle-2of8</guid>
      <description>&lt;h2&gt;
  
  
  &lt;strong&gt;Introduction&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Imagine that whenever you submit a form on a website, An invisible assistant comes in and checks everything again. Add additional details Or even send a welcome letter without you having to lift a finger. Laravel observers are like behind-the-scenes assistants who work quietly. And it's powerful to handle all the tasks when you need them. In this post, we'll dive into how observers work in Laravel, why they're your app's silent ninjas in model event handling. and how to get the most out of those events in real-world examples.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;What are Laravel Observers?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Laravel Observers are listener classes that help manage the lifecycle of your model by observing specific events, such as creating, updating, or deleting. Observers can define actions for each of these events. Keep your controllers and models clean and focused. The Observers act as "event experts" within your application Observers will handle the backend work required to improve your codebase. and improve organization and efficiency With event-driven work separation. Observers contribute to a more modular and maintainable application structure.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Why Use Observers?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Cleaner Controllers and Models:&lt;/strong&gt; Observers handle repeated actions, letting your controllers and models focus on their main jobs without distraction.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Code Reusability:&lt;/strong&gt; You can consolidate related actions in one place, making your code more readable and maintainable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Error Handling:&lt;/strong&gt; Observers help you avoid errors by automating tasks like data validation or background updates whenever a model changes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Automatic Event Handling:&lt;/strong&gt; Want to trigger an action every time a record is created or updated? Observers have your back.&lt;/p&gt;

&lt;p&gt;In short, Observers are fantastic for organizing logic that you want to execute during the various stages of your app’s lifecycle.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Eloquent Hooks Overview:&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;- Retrieved:&lt;/strong&gt; Triggered after a record is retrieved from the database.&lt;br&gt;
&lt;strong&gt;- Creating:&lt;/strong&gt; Fires just before a new record is created.&lt;br&gt;
&lt;strong&gt;- Created:&lt;/strong&gt; Executes after a new record is created successfully.&lt;br&gt;
&lt;strong&gt;- Updating:&lt;/strong&gt; Activates before an existing record is updated.&lt;br&gt;
&lt;strong&gt;- Updated:&lt;/strong&gt; Fires after a record has been updated.&lt;br&gt;
&lt;strong&gt;- Saving:&lt;/strong&gt; Runs before a record is saved, whether it's a new creation or an update.&lt;br&gt;
&lt;strong&gt;- Saved:&lt;/strong&gt; Occurs after a record has been saved, whether newly created or updated.&lt;br&gt;
&lt;strong&gt;- Deleting:&lt;/strong&gt; Initiates before a record is deleted or soft-deleted.&lt;br&gt;
&lt;strong&gt;- Deleted:&lt;/strong&gt; Activates after a record is deleted or soft-deleted.&lt;br&gt;
&lt;strong&gt;- Restoring:&lt;/strong&gt; Fires before a soft-deleted record is restored.&lt;br&gt;
&lt;strong&gt;- Restored:&lt;/strong&gt; Runs after a soft-deleted record has been successfully restored.&lt;/p&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;Step-by-Step Guide: How to Create and Use Observers&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Let's discuss Observers with a real-world example. Imagine we’re building a blogging app, and every time a user publishes a post, we want to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Automatically generate a slug from the title.&lt;/li&gt;
&lt;li&gt;Notify an admin.&lt;/li&gt;
&lt;li&gt;Record the publish date.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here’s how we can make this happen with Laravel Observers!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Create the Observer Class&lt;/strong&gt;&lt;br&gt;
Laravel makes it easy to generate an observer class. Run this command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:observer PostObserver --model=Post
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will generate a &lt;code&gt;PostObserver&lt;/code&gt; class in the &lt;code&gt;app/Observers&lt;/code&gt; directory and link it to our &lt;code&gt;Post&lt;/code&gt; model.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Define the Events in the Observer&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Open up the &lt;code&gt;PostObserver&lt;/code&gt; class, and you’ll see some handy methods already in place. Each method corresponds to a model event, like &lt;code&gt;creating&lt;/code&gt;, &lt;code&gt;updating&lt;/code&gt;, &lt;code&gt;deleting&lt;/code&gt;, and more.&lt;/p&gt;

&lt;p&gt;Let’s add our custom logic to the creating event so that it generates a slug and records the publish date:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use Illuminate\Support\Str;
class PostObserver
{
   public function creating(Post $post)
   {
       $post-&amp;gt;slug = Str::slug($post-&amp;gt;title);
       $post-&amp;gt;published_at = now();
   }

   public function created(Post $post)
   {
      Notification::send(User::admin(), new PostPublishedNotification($post));
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3: Register the Observer&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Laravel offers two ways to do this: the &lt;code&gt;ObservedBy&lt;/code&gt; attribute on the model or manually using the observe method&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1.Using the &lt;code&gt;ObservedBy&lt;/code&gt; Attribute&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you’re working with Laravel 10+, you can use the &lt;code&gt;ObservedBy&lt;/code&gt; attribute directly on your model. This attribute simplifies Observer registration by automatically linking the Observer to the model:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use App\Observers\PostObserver;
use Illuminate\Database\Eloquent\Concerns\ObservedBy;

#[ObservedBy(PostObserver::class)]
class Post extends Model
{
   // Your Post model code
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This approach is clean and keeps the Observer registration with the model itself, reducing setup steps and keeping your &lt;code&gt;AppServiceProvider&lt;/code&gt; untouched.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.Manually Registering the Observer&lt;/strong&gt;&lt;br&gt;
If you prefer (or are working in a Laravel version prior to 10), you can manually register the Observer in the &lt;code&gt;AppServiceProvider&lt;/code&gt;’s &lt;code&gt;boot&lt;/code&gt; method:&lt;/p&gt;

&lt;p&gt;In your &lt;code&gt;App\Providers\AppServiceProvider.php&lt;/code&gt;, add the &lt;code&gt;observe&lt;/code&gt; method to link the Observer to the model:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use App\Models\Post;
use App\Observers\PostObserver;

public function boot()
{
   Post::observe(PostObserver::class);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once registered, Laravel will trigger your Observer’s methods whenever the corresponding events occur on the &lt;code&gt;Post&lt;/code&gt; model.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4: Testing Your Observer&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To see your observer in action, try creating or updating a post in your app. The slug will generate automatically, the publish date will set itself, and our hypothetical admin will receive a notification. Observers make all this happen quietly, just like a true ninja.&lt;/p&gt;




&lt;p&gt;Thanks for reading! I hope this sparked some fresh ideas for your projects. If you're interested in bringing quality development to life, feel free to reach out—I’d love to connect and explore how we can make it happen.&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>php</category>
    </item>
    <item>
      <title>Crafting a Laravel Search Macro: A Quick Guide</title>
      <dc:creator>Dharmik Bhadkoliya</dc:creator>
      <pubDate>Fri, 08 Dec 2023 09:23:39 +0000</pubDate>
      <link>https://dev.to/dharmik225/crafting-a-laravel-search-macro-a-quick-guide-cic</link>
      <guid>https://dev.to/dharmik225/crafting-a-laravel-search-macro-a-quick-guide-cic</guid>
      <description>&lt;p&gt;Macro is a powerful Laravel framework feature.You can apply Laravel Macros to expand on the functionality of Laravel components.The Macroable trait allows macros to be defined on any class.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Where can I apply a macro?&lt;/strong&gt;&lt;br&gt;
If you're doing the same thing over and over again with Laravel components in your system, think about using a macro. It makes your code clearer and easier to reuse.&lt;/p&gt;

&lt;p&gt;For example, let's make a macro that adds a search feature to every model in our Laravel project.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Integration Steps:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Install Laravel and Create a New Project&lt;/strong&gt;&lt;br&gt;
First, make sure you have Laravel installed on your computer. If not, you can install it by following the instructions in the official Laravel documentation. After installing Laravel, open your terminal or command prompt and type the following command to create a new Laravel project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;composer create-project laravel/laravel MacrosApp
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you already have an existing Laravel project, you can use it to build macros and enhance its functionality. Simply navigate to your project's root directory in the terminal and proceed with the following steps.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Migrate &amp;amp; Seed the Database&lt;/strong&gt;&lt;br&gt;
Now that you've set up your Laravel project, the next step is to migrate and seed the database. This will create the necessary tables and populate them with sample data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;(a)Seed the Database:&lt;/strong&gt;&lt;br&gt;
Open the &lt;strong&gt;database/seeders/DatabaseSeeder.php&lt;/strong&gt; file. You'll find code that seeds the database with sample data. Uncomment this code by removing the // at the beginning of the lines.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;


class DatabaseSeeder extends Seeder
{
    public function run(): void {
        \App\Models\User::factory(10)-&amp;gt;create(); //Uncomment this line
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;(b)Run Migrations &amp;amp; Seed:&lt;/strong&gt;&lt;br&gt;
Open your terminal or command prompt, navigate to your project's root directory, and execute the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan migrate --seed
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3: Create a Search Macro&lt;/strong&gt;&lt;br&gt;
To enhance search functionality in your Laravel project, we'll add a custom search macro. Open the &lt;strong&gt;App\Providers\AppServiceProvider&lt;/strong&gt; file and define the macro within the &lt;strong&gt;boot&lt;/strong&gt; method.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;(a)Add a Simple Search Macro for a Single Attribute&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use Illuminate\Database\Eloquent\Builder;

//...
public function boot(): void
    {
       Builder::macro('search', function(string $attribute, string $searchTerm) {
                    return $this-&amp;gt;where($attribute, 'LIKE', "%{$searchTerm}%");
        });
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;(b)Extend the Search Macro to Handle Multiple Attributes.&lt;/strong&gt;&lt;br&gt;
To accommodate searching across multiple attributes, we'll modify the search macro to accept an array of attributes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use Illuminate\Support\Arr;
use Illuminate\Database\Eloquent\Builder;


public function boot(): void
    {
       Builder::macro('search', function($attributes, string $searchTerm) {
        foreach(Arr::wrap($attributes) as $attribute) {
            $this-&amp;gt;orWhere($attribute, 'LIKE', "%{$searchTerm}%");
        }
        return $this;
        });
    }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This extended search macro allows you to specify an array of attributes, making it more versatile for searching across multiple fields. The &lt;strong&gt;orWhere&lt;/strong&gt; method is used to build a query that matches any of the specified attributes with the given search term.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4 : How to apply the macro for searching&lt;/strong&gt;&lt;br&gt;
Now, use the following macro to add a search to not just the User model but all models:&lt;br&gt;
Open the &lt;strong&gt;routes/web.php&lt;/strong&gt; file in your project. Add the following code to demonstrate using the search macro in routes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php


use App\Models\User;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    // searching a single column
    return User::search('email','example.com')-&amp;gt;get();

   // searching on multiple columns
   return App\Models\User::search('name', 'mr')-&amp;gt;search('email', 'example.org')-&amp;gt;get();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we are using the search macro to find users by email and perform a combined search by name and email. Adjust the attribute names and search terms based on your actual model attributes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion:&lt;/strong&gt;&lt;br&gt;
To sum it up, this guide shows how to use Laravel macros to make searching in your project easier. With a simple setup process and a search macro that works for one or multiple attributes, your code becomes cleaner and more adaptable. By following the steps and applying the search macro to your controllers &amp;amp; routes, you can quickly add search features to your models, improving your code's simplicity and efficiency.&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>php</category>
      <category>macro</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Mastering Traits: The First Step to Clean &amp; Efficient Laravel Code</title>
      <dc:creator>Dharmik Bhadkoliya</dc:creator>
      <pubDate>Tue, 05 Dec 2023 04:35:26 +0000</pubDate>
      <link>https://dev.to/dharmik225/mastering-traits-the-first-step-to-clean-efficient-laravel-code-48l2</link>
      <guid>https://dev.to/dharmik225/mastering-traits-the-first-step-to-clean-efficient-laravel-code-48l2</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Laravel is a widely-used PHP framework for building web applications. It's known for its clean and powerful code. Within Laravel, there's a useful feature called 'traits' that helps you reuse and organize your code efficiently. In this guide, we'll take a closer look at Laravel traits. We'll explain what they are, why they matter, and show you how to use them effectively in your Laravel projects, step by step.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Are Traits in Laravel?
&lt;/h2&gt;

&lt;p&gt;In Laravel, traits are a way to reuse methods in multiple classes. They provide a mechanism for code reuse without the need for multiple inheritance, solving the problem of inheriting from multiple classes, which PHP can't handle. Traits are basically groups of methods that can be included within classes, giving you a flexible way to expand and share functionality.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Are Traits Useful in Laravel?
&lt;/h2&gt;

&lt;p&gt;There are various benefits to using traits in Laravel:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code Reusability:&lt;/strong&gt;  Traits enable you to specify and reuse common functionality across several classes, minimizing redundancy and making your code more maintainable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Structure:&lt;/strong&gt;  Traits improve with code structure by grouping relevant methods together, hence improving code readability and reliability.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Flexibility:&lt;/strong&gt;  You can include multiple traits  in a single class, which allows you the ability to mix and match functionality as needed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Avoiding Multiple Inheritance Issues:&lt;/strong&gt;  Because PHP does not support multiple inheritance, traits allow you equal functionality without any issues.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 1: Install Laravel and Create a New Project
&lt;/h2&gt;

&lt;p&gt;First, make sure you have Laravel installed on your computer. If not, you can install it by following the instructions in the official &lt;a href="https://laravel.com/docs/10.x/installation#creating-a-laravel-project" rel="noopener noreferrer"&gt;Laravel documentation.&lt;/a&gt; After installing Laravel, open your terminal or command prompt and type the following command to create a new Laravel project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;composer create-project laravel/laravel TraitApp

OR

laravel new TraitApp

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 2: Create a Trait
&lt;/h2&gt;

&lt;p&gt;Create a new trait in the Laravel project. In general, traits are placed in the &lt;strong&gt;app/Traits&lt;/strong&gt; directory. Let's start with a basic &lt;strong&gt;LogTrait.php&lt;/strong&gt; trait:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
namespace App\Traits;

trait LogTrait {
    public function log($message) {
        \Log::info($message);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 3: Apply the Trait in a Class
&lt;/h2&gt;

&lt;p&gt;Let's put the LogTrait to use in a class. Create a new controller or any class where you would like to log messages:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Http\Controllers;
use App\Traits\LogTrait;
use Illuminate\Http\Request;

class HomeController extends Controller
{
     use LogTrait;

     function index() : String {
        $this-&amp;gt;log('LogTrait is Working !!');
        return 'Message logged!';
     }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 4 : Test the Trait
&lt;/h2&gt;

&lt;p&gt;Create a route in your &lt;strong&gt;routes/web.php&lt;/strong&gt; file to test the trait:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Route::get('/',[HomeController::class,'index']);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When you refresh your browser, the message "LogTrait is Working!!" will be logged, demonstrating the use of the LogTrait.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion:
&lt;/h2&gt;

&lt;p&gt;In this guide, we explored the concept of Laravel traits and how they enhance code organization and reusability. By implementing these techniques, you can streamline your Laravel projects, leading to cleaner and more efficient code. Happy coding!&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>php</category>
      <category>trait</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
