<?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"><channel><title><![CDATA[Feqy's Tech]]></title><description><![CDATA[Hello world 👋, I'm a developer sharing my thoughts (📝) during my journey as a developer, consider subscribing so you can be notified once I shared anything]]></description><link>https://thefeqy.hashnode.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1700175089033/O_ZuzwLfM.png</url><title>Feqy&apos;s Tech</title><link>https://thefeqy.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Sun, 08 Nov 2026 14:02:23 GMT</lastBuildDate><atom:link href="https://thefeqy.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Streamlining Laravel Projects with Laravel Model Status]]></title><description><![CDATA[Managing user or model statuses is a common task in Laravel projects. Whether you're building a simple application or a large-scale system, adding and…]]></description><link>https://thefeqy.hashnode.dev/laravel-model-status</link><guid isPermaLink="true">https://thefeqy.hashnode.dev/laravel-model-status</guid><category><![CDATA[Laravel]]></category><dc:creator><![CDATA[Muhammed ElFeqy]]></dc:creator><pubDate>Sat, 18 Jan 2025 15:58:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1737215833036/46b8881d-c2f3-43f6-84a3-5f796fa21b46.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Managing user or model statuses is a common task in Laravel projects. Whether you're building a simple application or a large-scale system, adding and handling status columns often becomes repetitive and time-consuming. That's where <strong>Laravel Model Status</strong> comes in—a lightweight package designed to simplify this process and provide a seamless workflow for status management in Laravel models.</p>
<hr />
<h2 id="heading-the-problem">The Problem</h2>
<p>In many Laravel projects, there’s often a need to manage the "status" of a model, such as marking users as <code>active</code> or <code>inactive</code>, or controlling whether certain entities are accessible. Typically, this involves:</p>
<ul>
<li><p>Adding a <code>status</code> column to the database schema.</p>
</li>
<li><p>Writing scopes to filter models based on their status.</p>
</li>
<li><p>Adding middleware to restrict access for inactive users.</p>
</li>
<li><p>Repeating this logic across multiple projects.</p>
</li>
</ul>
<p>This repetitive process consumes valuable development time and can introduce inconsistencies between projects.</p>
<hr />
<h2 id="heading-the-solution-laravel-model-status">The Solution: Laravel Model Status</h2>
<p><strong>Laravel Model Status</strong> was created to address this problem. The package provides a consistent and configurable way to manage statuses in Laravel models while reducing redundancy and improving code readability.</p>
<hr />
<h2 id="heading-key-features">Key Features</h2>
<ul>
<li><p><strong>Configurable Status Column</strong>: Define the name, default value, and length of the <code>status</code> column via a configuration file.</p>
</li>
<li><p><strong>Global Scope for Active Models</strong>: Automatically filter models to return only active records unless explicitly overridden.</p>
</li>
<li><p><strong>Middleware for User Activity</strong>: Ensure only active users can access protected routes.</p>
</li>
<li><p><strong>Activation and Deactivation Methods</strong>: Easily activate or deactivate models using built-in methods.</p>
</li>
<li><p><strong>Custom Artisan Command</strong>: Create models and migrations with a <code>status</code> column and include the necessary trait automatically.</p>
</li>
</ul>
<hr />
<h2 id="heading-installation">Installation</h2>
<p>You can install the package via Composer:</p>
<pre><code class="lang-bash">composer require thefeqy/laravel-model-status
</code></pre>
<h2 id="heading-configuration">Configuration</h2>
<p>After installation, publish the configuration file:</p>
<pre><code class="lang-bash">php artisan vendor:publish --tag=config
</code></pre>
<p>The configuration file allows you to customize the <code>status</code> column and its behavior:</p>
<pre><code class="lang-php"><span class="hljs-keyword">return</span> [
    <span class="hljs-string">'column_name'</span> =&gt; <span class="hljs-string">'status'</span>, <span class="hljs-comment">// Name of the status column</span>
    <span class="hljs-string">'default_value'</span> =&gt; <span class="hljs-string">'active'</span>, <span class="hljs-comment">// Default value for the active state</span>
    <span class="hljs-string">'inactive_value'</span> =&gt; <span class="hljs-string">'inactive'</span>, <span class="hljs-comment">// Value for the inactive state</span>
    <span class="hljs-string">'column_length'</span> =&gt; <span class="hljs-number">10</span>, <span class="hljs-comment">// Maximum length of the status column</span>
];
</code></pre>
<hr />
<h2 id="heading-usage">Usage</h2>
<p>Adding the Trait To use the package, include the <code>HasActiveScope</code> trait in your model:</p>
<pre><code class="lang-php"><span class="hljs-keyword">use</span> <span class="hljs-title">Thefeqy</span>\<span class="hljs-title">ModelStatus</span>\<span class="hljs-title">Traits</span>\<span class="hljs-title">HasActiveScope</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleModel</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span>
</span>{
    <span class="hljs-keyword">use</span> <span class="hljs-title">HasActiveScope</span>;

    <span class="hljs-keyword">protected</span> $fillable = [<span class="hljs-string">'name'</span>];
}
</code></pre>
<hr />
<h2 id="heading-real-world-example-product-management">Real-World Example: Product Management</h2>
<p>Imagine you are building an e-commerce platform where products can be <code>active</code> or <code>inactive</code>, determining their visibility to customers. Let’s use the package to handle this efficiently.</p>
<h3 id="heading-create-the-model-and-migration">Create the Model and Migration</h3>
<p>Use the <code>make:model-status</code> command to create the <code>Product</code> model and migration with a <code>status</code> column:</p>
<pre><code class="lang-bash">php artisan make:model-status Product
</code></pre>
<h4 id="heading-this-command-will">This command will:</h4>
<ul>
<li><p>Create the <code>Product</code> model with the <code>HasActiveScope</code> trait.</p>
</li>
<li><p>Generate a migration with the configured <code>status</code> column.</p>
</li>
</ul>
<h4 id="heading-product-model">Product Model</h4>
<p>The generated model (app/Models/Product.php) will look like this:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Models</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Database</span>\<span class="hljs-title">Eloquent</span>\<span class="hljs-title">Factories</span>\<span class="hljs-title">HasFactory</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Database</span>\<span class="hljs-title">Eloquent</span>\<span class="hljs-title">Model</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Thefeqy</span>\<span class="hljs-title">ModelStatus</span>\<span class="hljs-title">Traits</span>\<span class="hljs-title">HasActiveScope</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Product</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span>
</span>{
    <span class="hljs-keyword">use</span> <span class="hljs-title">HasFactory</span>, <span class="hljs-title">HasActiveScope</span>;

    <span class="hljs-keyword">protected</span> $fillable = [<span class="hljs-string">'name'</span>, <span class="hljs-string">'price'</span>, <span class="hljs-string">'description'</span>];
}
</code></pre>
<h4 id="heading-migration">Migration</h4>
<p>The generated migration will include a status column:</p>
<pre><code class="lang-php">Schema::create(<span class="hljs-string">'products'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Blueprint $table</span>) </span>{
    $table-&gt;id();
    $table-&gt;string(<span class="hljs-string">'name'</span>);
    $table-&gt;text(<span class="hljs-string">'description'</span>)-&gt;nullable();
    $table-&gt;decimal(<span class="hljs-string">'price'</span>, <span class="hljs-number">10</span>, <span class="hljs-number">2</span>);
    $table-&gt;string(<span class="hljs-string">'status'</span>, <span class="hljs-number">10</span>)-&gt;default(<span class="hljs-string">'active'</span>); <span class="hljs-comment">// Configurable status column</span>
    $table-&gt;timestamps();
});
</code></pre>
<p>Run the migration:</p>
<pre><code class="lang-bash">php artisan migrate
</code></pre>
<h3 id="heading-activating-and-deactivating-products">Activating and Deactivating Products</h3>
<p>The <code>HasActiveScope</code> trait provides methods to <code>activate</code> and <code>deactivate</code> models dynamically:</p>
<h4 id="heading-activating-a-product">Activating a Product</h4>
<pre><code class="lang-php">$product = Product::find(<span class="hljs-number">1</span>);
<span class="hljs-keyword">if</span> ($product-&gt;activate()) {
    <span class="hljs-keyword">echo</span> <span class="hljs-string">"Product activated successfully!"</span>;
} <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">echo</span> <span class="hljs-string">"Failed to activate product."</span>;
}
</code></pre>
<h4 id="heading-deactivating-a-product">Deactivating a Product</h4>
<pre><code class="lang-php">$product = Product::withoutActive()-&gt;find(<span class="hljs-number">1</span>);
<span class="hljs-keyword">if</span> ($product-&gt;deactivate()) {
    <span class="hljs-keyword">echo</span> <span class="hljs-string">"Product deactivated successfully!"</span>;
} <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">echo</span> <span class="hljs-string">"Failed to deactivate product."</span>;
}
</code></pre>
<hr />
<h3 id="heading-querying-products">Querying Products</h3>
<p>Retrieve Only Active Products (Default Behavior)</p>
<pre><code class="lang-php">$activeProducts = Product::all(); <span class="hljs-comment">// Filters to only active products</span>
</code></pre>
<p>Retrieve All Products (Including Inactive)</p>
<pre><code class="lang-php">$allProducts = Product::withoutActive()-&gt;get();
</code></pre>
<hr />
<h2 id="heading-middleware-usage">Middleware Usage</h2>
<p>The <code>EnsureAuthenticatedUserIsActive</code> middleware restricts access for inactive users. You can also use it to reactivate suspended accounts by guiding users to contact support.</p>
<h3 id="heading-example-route-setup">Example Route Setup</h3>
<p>Instead of registering a string alias, use the middleware class directly:</p>
<pre><code class="lang-php"><span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">Route</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Thefeqy</span>\<span class="hljs-title">ModelStatus</span>\<span class="hljs-title">Middleware</span>\<span class="hljs-title">EnsureAuthorizedUserIsActive</span>;

Route::middleware([<span class="hljs-string">'auth'</span>, EnsureAuthenticatedUserIsActive::class])-&gt;group(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    Route::get(<span class="hljs-string">'/dashboard'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'Welcome to your dashboard!'</span>;
    });
});
</code></pre>
<h3 id="heading-behavior">Behavior</h3>
<ul>
<li><p>Inactive users attempting to access routes:</p>
<ul>
<li><p>Are logged out.</p>
</li>
<li><p>Receive a 403 Forbidden response with the message:</p>
</li>
</ul>
</li>
</ul>
<pre><code class="lang-php">This account is suspended. Please contact the administrator.
</code></pre>
<h2 id="heading-admin-panel-example-managing-products">Admin Panel Example: Managing Products</h2>
<p>In the admin panel, administrators can view all products (including inactive ones) and toggle their status.</p>
<h4 id="heading-controller-example">Controller Example:</h4>
<pre><code class="lang-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">Product</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AdminProductController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">index</span>(<span class="hljs-params"></span>)
    </span>{
        $products = Product::withoutActive()-&gt;get(); <span class="hljs-comment">// Get all products</span>
        <span class="hljs-keyword">return</span> view(<span class="hljs-string">'admin.products.index'</span>, compact(<span class="hljs-string">'products'</span>));
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">activate</span>(<span class="hljs-params">Product $product</span>)
    </span>{
        <span class="hljs-keyword">if</span> ($product-&gt;activate()) {
            <span class="hljs-keyword">return</span> redirect()-&gt;back()-&gt;with(<span class="hljs-string">'success'</span>, <span class="hljs-string">'Product activated successfully!'</span>);
        }

        <span class="hljs-keyword">return</span> redirect()-&gt;back()-&gt;with(<span class="hljs-string">'error'</span>, <span class="hljs-string">'Failed to activate product.'</span>);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">deactivate</span>(<span class="hljs-params">Product $product</span>)
    </span>{
        <span class="hljs-keyword">if</span> ($product-&gt;deactivate()) {
            <span class="hljs-keyword">return</span> redirect()-&gt;back()-&gt;with(<span class="hljs-string">'success'</span>, <span class="hljs-string">'Product deactivated successfully!'</span>);
        }

        <span class="hljs-keyword">return</span> redirect()-&gt;back()-&gt;with(<span class="hljs-string">'error'</span>, <span class="hljs-string">'Failed to deactivate product.'</span>);
    }
}
</code></pre>
<hr />
<h2 id="heading-github-repository">GitHub Repository</h2>
<p>The package is open-source and available on GitHub. Feel free to explore, contribute, or raise issues: <a target="_blank" href="https://github.com/thefeqy/laravel-model-status">https://github.com/thefeqy/laravel-model-status</a></p>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>Laravel Model Status streamlines the process of managing model statuses in Laravel projects. Whether you’re working on an e-commerce platform, a user management system, or any other project requiring status handling, this package simplifies your workflow and ensures consistency across your applications.</p>
<p>Try it today and make status management effortless! 🚀</p>
]]></content:encoded></item><item><title><![CDATA[Observers in Laravel: Simplifying Model Event Handling With Real-World Examples]]></title><description><![CDATA[In Laravel, Observers are classes used to handle model events cleanly and efficiently. Events like creating, created, updating, updated, deleting, and…]]></description><link>https://thefeqy.hashnode.dev/observers-in-laravel-simplifying-model-event-handling-with-real-world-examples</link><guid isPermaLink="true">https://thefeqy.hashnode.dev/observers-in-laravel-simplifying-model-event-handling-with-real-world-examples</guid><category><![CDATA[Laravel]]></category><category><![CDATA[design patterns]]></category><category><![CDATA[PHP]]></category><dc:creator><![CDATA[Muhammed ElFeqy]]></dc:creator><pubDate>Tue, 26 Nov 2024 18:39:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1732646246941/39156196-f5c6-4978-9055-8f53eecb5dd6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In Laravel, <strong>Observers</strong> are classes used to handle model events cleanly and efficiently. Events like <code>creating</code>, <code>created</code>, <code>updating</code>, <code>updated</code>, <code>deleting</code>, and <code>deleted</code> occur when a model undergoes specific changes. Observers allow us to separate this logic from controllers or models, keeping the codebase clean and modular.</p>
<hr />
<h3 id="heading-why-use-observers"><strong>Why Use Observers?</strong></h3>
<ol>
<li><p><strong>Separation of Concerns</strong>: Keeps event-handling logic out of models.</p>
</li>
<li><p><strong>Reusability</strong>: The same observer can handle events for multiple models.</p>
</li>
<li><p><strong>Cleaner Code</strong>: Reduces clutter in the model or controller.</p>
</li>
</ol>
<h3 id="heading-real-world-examples-of-the-observer-pattern"><strong>Real-World Examples of the Observer Pattern</strong></h3>
<p>The Observer pattern is commonly used when you want certain parts of your system to react to changes in an object automatically. Here are some real-world examples where the pattern fits naturally:</p>
<h3 id="heading-1-sending-emails-or-notifications"><strong>1. Sending Emails or Notifications</strong></h3>
<ul>
<li><p><strong>Scenario</strong>: When a user registers on a website, you might want to send a welcome email or notify admins.</p>
</li>
<li><p><strong>Observer's Role</strong>: Automatically trigger email or notification logic when the <code>User</code> model's <code>created</code> event is fired.</p>
</li>
</ul>
<h3 id="heading-2-inventory-management-in-e-commerce"><strong>2. Inventory Management in E-commerce</strong></h3>
<ul>
<li><p><strong>Scenario</strong>: When an order is placed, the stock levels of items in the order should be reduced.</p>
</li>
<li><p><strong>Observer's Role</strong>: Listen to the <code>created</code> event of an <code>Order</code> model to automatically adjust product inventory.</p>
</li>
</ul>
<h3 id="heading-3-automated-billing"><strong>3. Automated Billing</strong></h3>
<ul>
<li><p><strong>Scenario</strong>: If a subscription is updated or canceled, the billing system should react accordingly.</p>
</li>
<li><p><strong>Observer's Role</strong>: Listen for <code>updated</code> or <code>deleted</code> events on the <code>Subscription</code> model to handle billing updates.</p>
</li>
</ul>
<h3 id="heading-setting-up-observers-in-laravel"><strong>Setting Up Observers in Laravel</strong></h3>
<p>Here’s how to implement and use observers step-by-step:</p>
<h3 id="heading-1-create-an-observer-class"><strong>1. Create an Observer Class</strong></h3>
<p>Use the Artisan command to generate an observer:</p>
<pre><code class="lang-bash">php artisan make:observer PostObserver --model=Post
</code></pre>
<p>This creates an <code>PostObserver</code> class in the <code>App\Observers</code> directory. The <code>—model=Post</code> flag associates the observer with the <code>Post</code> model.</p>
<h3 id="heading-2-define-event-methods-in-the-observer"><strong>2. Define Event Methods in the Observer</strong></h3>
<p>Edit the <code>PostObserver</code> class to handle desired events:</p>
<pre><code class="lang-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Observers</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Str</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">Post</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PostObserver</span>
</span>{
    <span class="hljs-comment">/**
     * Handle the Post "saving" event.
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">saving</span>(<span class="hljs-params">Post $post</span>)
    </span>{
        <span class="hljs-keyword">if</span> (!$post-&gt;slug) {
            $post-&gt;slug = Str::slug($post-&gt;title); <span class="hljs-comment">// Generate slug from title</span>
        }
    }
}
</code></pre>
<h3 id="heading-3-register-the-observer"><strong>3. Register the Observer</strong></h3>
<p>Register the observer in the <code>boot</code> method of the <code>App\Providers\AppServiceProvider</code> class:</p>
<pre><code class="lang-php"><span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">Post</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Observers</span>\<span class="hljs-title">PostObserver</span>;

<span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">boot</span>(<span class="hljs-params"></span>)
</span>{
    Post::observe(PostObserver::class);
}
</code></pre>
<h3 id="heading-4-test-the-observer"><strong>4. Test the Observer</strong></h3>
<p>Create or update a blog post to see the slug generation in action:</p>
<pre><code class="lang-php"><span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">Post</span>;

<span class="hljs-comment">// Create a post without a slug</span>
$post = Post::create([
    <span class="hljs-string">'title'</span> =&gt; <span class="hljs-string">'How to Use Laravel Observers'</span>,
    <span class="hljs-string">'content'</span> =&gt; <span class="hljs-string">'Observers are a great way to handle events.'</span>,
]);

<span class="hljs-comment">// Check the generated slug</span>
dd($post-&gt;slug); <span class="hljs-comment">// Output: "how-to-use-laravel-observers"</span>
</code></pre>
<h3 id="heading-5-check-database"><strong>5. Check Database</strong></h3>
<p>When you inspect the database, you’ll see that the <code>slug</code> column is populated automatically:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>ID</strong></td><td><strong>Title</strong></td><td><strong>Slug</strong></td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>How to Use Laravel Observers</td><td>how-to-use-laravel-observers</td></tr>
</tbody>
</table>
</div><h3 id="heading-observer-event-methods"><strong>Observer Event Methods</strong></h3>
<p>Here’s a quick reference for available methods in an observer:</p>
<ul>
<li><p><code>creating</code> / <code>created</code>: Before/after a model is created.</p>
</li>
<li><p><code>updating</code> / <code>updated</code>: Before/after a model is updated.</p>
</li>
<li><p><code>saving</code> / <code>saved</code>: Before/after a model is created or updated.</p>
</li>
<li><p><code>deleting</code> / <code>deleted</code>: Before/after a model is deleted.</p>
</li>
<li><p><code>restoring</code> / <code>restored</code>: Before/after a soft-deleted model is restored.</p>
</li>
</ul>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>The Observer pattern is a powerful tool in Laravel for handling model events. By implementing it, you can simplify repetitive tasks like sending notifications, maintaining logs, or updating related data. Observers improve code clarity, follow best practices like <strong>Separation of Concerns</strong>, and make applications easier to maintain.</p>
]]></content:encoded></item><item><title><![CDATA[PHP 8.4 Is Here !]]></title><description><![CDATA[Discover the exciting new features of PHP 8.4, including property hooks, asymmetric visibility, multibyte trim functions, and more. Learn with detailed…]]></description><link>https://thefeqy.hashnode.dev/php-84-is-here</link><guid isPermaLink="true">https://thefeqy.hashnode.dev/php-84-is-here</guid><category><![CDATA[PHP]]></category><category><![CDATA[php8]]></category><dc:creator><![CDATA[Muhammed ElFeqy]]></dc:creator><pubDate>Fri, 22 Nov 2024 22:30:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1732314448180/ff461c12-b98b-48c8-9997-df6c04ef6d6f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>PHP continues to evolve as a versatile and developer-friendly language, and its latest release, PHP 8.4, is no exception. Packed with enhancements designed to simplify syntax, improve performance, and make code more expressive, this version further strengthens PHP's position as a leading choice for web development. In this article, we’ll delve into the most notable new features of PHP 8.4, complete with descriptions and practical examples to help you leverage them effectively.</p>
<hr />
<h3 id="heading-1-property-hooks"><strong>1. Property Hooks</strong></h3>
<p>Property Hooks allow developers to define custom behavior when accessing or modifying class properties, reducing the need for boilerplate getter and setter methods.</p>
<p><em>Example:</em></p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">bool</span> $isModified = <span class="hljs-literal">false</span>;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> $first, <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> $last</span>) </span>{}

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $fullName {
        get =&gt; <span class="hljs-keyword">$this</span>-&gt;first . <span class="hljs-string">' '</span> . <span class="hljs-keyword">$this</span>-&gt;last;
        set {
            [<span class="hljs-keyword">$this</span>-&gt;first, <span class="hljs-keyword">$this</span>-&gt;last] = explode(<span class="hljs-string">' '</span>, $value, <span class="hljs-number">2</span>);
            <span class="hljs-keyword">$this</span>-&gt;isModified = <span class="hljs-literal">true</span>;
        }
    }
}

$user = <span class="hljs-keyword">new</span> User(<span class="hljs-string">'John'</span>, <span class="hljs-string">'Doe'</span>);
<span class="hljs-keyword">echo</span> $user-&gt;fullName; <span class="hljs-comment">// Outputs: John Doe</span>
$user-&gt;fullName = <span class="hljs-string">'Jane Smith'</span>;
<span class="hljs-keyword">echo</span> $user-&gt;fullName; <span class="hljs-comment">// Outputs: Jane Smith</span>
</code></pre>
<p>In this example, accessing <code>$user-&gt;fullName</code> triggers the <code>get</code> hook, while assigning a value to it triggers the <code>set</code> hook, allowing for custom logic during these operations.</p>
<h3 id="heading-2-asymmetric-visibility"><strong>2. Asymmetric Visibility</strong></h3>
<p>Asymmetric Visibility enables different visibility levels for reading and writing class properties, offering more granular control over property access.</p>
<p><em>Example:</em></p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Product</span> </span>{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">private</span>(set) <span class="hljs-keyword">float</span> $price;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params"><span class="hljs-keyword">float</span> $price</span>) </span>{
        <span class="hljs-keyword">$this</span>-&gt;price = $price;
    }
}

$product = <span class="hljs-keyword">new</span> Product(<span class="hljs-number">99.99</span>);
<span class="hljs-keyword">echo</span> $product-&gt;price; <span class="hljs-comment">// Outputs: 99.99</span>
$product-&gt;price = <span class="hljs-number">79.99</span>; <span class="hljs-comment">// Error: Cannot modify readonly property</span>
</code></pre>
<p>Here, the <code>price</code> property is publicly readable but can only be modified within the class, preventing external modification.</p>
<h3 id="heading-3-chaining-new-without-parentheses"><strong>3. Chaining</strong> <code>new</code> Without Parentheses</h3>
<p>PHP 8.4 allows method chaining directly on new class instances without requiring parentheses around the instantiation, simplifying syntax.</p>
<p><em>Example:</em></p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Request</span> </span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">withMethod</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $method</span>): <span class="hljs-title">static</span> </span>{
        <span class="hljs-comment">// Set the method</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">withUri</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $uri</span>): <span class="hljs-title">static</span> </span>{
        <span class="hljs-comment">// Set the URI</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>;
    }
}

$request = <span class="hljs-keyword">new</span> Request()-&gt;withMethod(<span class="hljs-string">'GET'</span>)-&gt;withUri(<span class="hljs-string">'/home'</span>);
</code></pre>
<p>This feature enhances code readability by eliminating unnecessary parentheses during method chaining.</p>
<h3 id="heading-4-new-array-find-functions"><strong>4. New Array Find Functions</strong></h3>
<p>PHP 8.4 introduces several array functions to streamline common operations:</p>
<ul>
<li><p><code>array_find()</code>: Returns the first element that satisfies a given condition.</p>
</li>
<li><p><code>array_find_key()</code>: Returns the key of the first element that satisfies a given condition.</p>
</li>
<li><p><code>array_any()</code>: Checks if any array element satisfies a given condition.</p>
</li>
<li><p><code>array_all()</code>: Checks if all array elements satisfy a given condition.</p>
</li>
</ul>
<p><em>Example:</em></p>
<pre><code class="lang-php">$array = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

$firstEven = array_find($array, <span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$value</span>) =&gt; $<span class="hljs-title">value</span> % 2 === 0)</span>;
<span class="hljs-keyword">echo</span> $firstEven; <span class="hljs-comment">// Outputs: 2</span>

$hasNegative = array_any($array, <span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$value</span>) =&gt; $<span class="hljs-title">value</span> &lt; 0)</span>;
var_dump($hasNegative); <span class="hljs-comment">// Outputs: bool(false)</span>
</code></pre>
<p>These functions provide concise and readable ways to perform common array operations.</p>
<h3 id="heading-5-html5-parsing-support"><strong>5. HTML5 Parsing Support</strong></h3>
<p>PHP 8.4 enhances the DOM extension with support for HTML5, introducing new classes in the <code>Dom</code> namespace that are compliant with the WHATWG specification.</p>
<p><em>Example:</em></p>
<pre><code class="lang-php"><span class="hljs-keyword">use</span> <span class="hljs-title">Dom</span>\<span class="hljs-title">HTMLDocument</span>;

$html = <span class="hljs-string">'&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;body&gt;&lt;p&gt;Hello, World!&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;'</span>;
$doc = HTMLDocument::createFromString($html);
<span class="hljs-keyword">echo</span> $doc-&gt;body-&gt;textContent; <span class="hljs-comment">// Outputs: Hello, World!</span>
</code></pre>
<p>This update allows for more accurate parsing and manipulation of HTML5 documents.</p>
<h3 id="heading-6-multibyte-trim-functions"><strong>6. Multibyte Trim Functions</strong></h3>
<p>New multibyte string functions have been added to handle trimming operations on strings with multibyte characters:</p>
<ul>
<li><p><code>mb_trim()</code>: Trims whitespace from both ends of a string.</p>
</li>
<li><p><code>mb_ltrim()</code>: Trims whitespace from the beginning of a string.</p>
</li>
<li><p><code>mb_rtrim()</code>: Trims whitespace from the end of a string.</p>
</li>
</ul>
<p><em>Example:</em></p>
<pre><code class="lang-php">$str = <span class="hljs-string">" こんにちは "</span>;
$trimmed = mb_trim($str);
<span class="hljs-keyword">echo</span> $trimmed; <span class="hljs-comment">// Outputs: こんにちは</span>
</code></pre>
<p>These functions ensure proper handling of multibyte characters during trimming operations.</p>
<h3 id="heading-7-just-in-time-jit-compiler-enhancements"><strong>7. Just-In-Time (JIT) Compiler Enhancements</strong></h3>
<p>PHP 8.4 includes improvements to the JIT compiler, resulting in better performance and reduced memory usage in certain scenarios.</p>
<p>These enhancements aim to optimize the execution of PHP scripts, particularly those that are CPU-intensive.</p>
<h3 id="heading-8-deprecation-of-implicit-nullable-types"><strong>8. Deprecation of Implicit Nullable Types</strong></h3>
<p>PHP 8.4 deprecates the implicit conversion of typed parameters with default <code>null</code> values to nullable types. Developers are now required to explicitly declare nullable types.</p>
<p><em>Example:</em></p>
<pre><code class="lang-php"><span class="hljs-comment">// Deprecated in PHP 8.4</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processData</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $data = <span class="hljs-literal">null</span></span>) </span>{
    <span class="hljs-comment">// ...</span>
}

<span class="hljs-comment">// Recommended in PHP 8.4</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processData</span>(<span class="hljs-params">?<span class="hljs-keyword">string</span> $data = <span class="hljs-literal">null</span></span>) </span>{
    <span class="hljs-comment">// ...</span>
}
</code></pre>
<p>This change promotes clearer type declarations and reduces potential ambiguities in code.</p>
<hr />
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>PHP 8.4 marks another milestone in the journey of the PHP language, bringing a host of features that enhance developer experience, boost productivity, and ensure better performance. From property hooks and asymmetric visibility to the introduction of multibyte trim functions and HTML5 parsing support, this update demonstrates PHP’s commitment to innovation and practicality. Whether you’re a seasoned developer or just getting started, these features empower you to write cleaner, more efficient, and modern PHP code.</p>
<p>As you explore PHP 8.4, take the time to incorporate these new tools into your projects. They not only simplify everyday tasks but also make your applications more robust and maintainable. So, update your environments, experiment with the features, and let PHP 8.4 elevate your coding experience to new heights! Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Error Handling In NodeTS]]></title><description><![CDATA[What Is Error Handling when you deploy your application to production, you need to make sure that your application is well tested for all possible…]]></description><link>https://thefeqy.hashnode.dev/error-handling-in-nodejs</link><guid isPermaLink="true">https://thefeqy.hashnode.dev/error-handling-in-nodejs</guid><category><![CDATA[Node.js]]></category><category><![CDATA[Express]]></category><category><![CDATA[error handling]]></category><category><![CDATA[MERN Stack]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Muhammed ElFeqy]]></dc:creator><pubDate>Sat, 16 Apr 2022 03:31:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649224181633/tdLHm7n1c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In your development process, you need to make debugging as easy as possible, you definitely don't want to see an <code>uncaughtException</code> that could crash your application. </p>
<h1 id="heading-what-is-error-handling">What Is Error Handling</h1>
<p>when you deploy your application to production, you need to make sure that your application is well tested for all possible scenarios. but you might heard before that handling errors in the world of <strong>NodeJS</strong>, could be a pain in the a**, I won't lie, it is already not that easy, however, it's not that hard too</p>
<p>all you need to do is prepare your application to properly handle your errors, and this is what we're gonna do in this article.</p>
<h1 id="heading-error-object">Error Object</h1>
<p>as <a target="_blank" href="https://nodejs.dev/learn/error-handling-in-nodejs/#error-objects">documentation</a> says: An error object is an object that is either an instance of the Error object or extends the Error class, provided in the Error core module.</p>
<p>here are some examples:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// throw an instance of the Error object</span>
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'An error occurred'</span>);
</code></pre>
<p>or, with a custom error class:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> CustomErrorHandler <span class="hljs-keyword">extends</span> <span class="hljs-built_in">Error</span> {
<span class="hljs-comment">// ...</span>
}

<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> CustomErrorHandler(<span class="hljs-string">'Custom Error ...'</span>);
</code></pre>
<h1 id="heading-how-to-handle-errors-in-our-application">How to handle errors in our application</h1>
<p>you can simply use <code>try/catch</code> blocks, any raised exception within <code>try</code> block, is handled in the corresponding <code>catch</code> block.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">try</span> {
<span class="hljs-comment">// Some logic</span>
} <span class="hljs-keyword">catch</span> (error) {
<span class="hljs-comment">// Handle Error</span>
 <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'An error occurred'</span>);
}
</code></pre>
<p>if you're using <code>express</code>, you can easily catch and process raised errors by creating a custom error handler as follows: <code>file: index.ts</code></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> express, { NextFunction, Request, Response } <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>;
<span class="hljs-keyword">import</span> cors <span class="hljs-keyword">from</span> <span class="hljs-string">'cors'</span>;

<span class="hljs-keyword">const</span> app = express();
app.use(cors());

app.post(<span class="hljs-string">'/write-test'</span>, <span class="hljs-function">(<span class="hljs-params">req: Request, res: Response</span>) =&gt;</span> {
    <span class="hljs-keyword">try</span> {
        fs.writeFileSync(<span class="hljs-string">"programming.txt"</span>, undefinedvarible); <span class="hljs-comment">// this code should raise an exception</span>
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-comment">// Handle Error</span>
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'An error occurred'</span>);
    }
});

<span class="hljs-comment">// Last middleware</span>
app.use(<span class="hljs-function">(<span class="hljs-params">err:  <span class="hljs-built_in">Error</span>, req: Request, res: Response, next: NextFunction</span>) =&gt;</span> {
 <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">400</span>).send(<span class="hljs-string">'An error occurred'</span>);
})

app.listen(<span class="hljs-number">5000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Up &amp; Running'</span>));
</code></pre>
<blockquote>
<p>note: your custom error handler should be the last middleware in your application.</p>
</blockquote>
<p>But here's the thing, now you should add <code>try/catch</code> blocks in every action method, so you can catch the errors with the error handler that we just created.
this is horrible right? we should find another way that could save us a lot of time during our development process.</p>
<h1 id="heading-use-higher-order-function-curring">Use higher-order function (Curring)</h1>
<p>a higher-order function is a function that accepts an array as a parameter and/or returns a function.</p>
<blockquote>
<p>you can read more about higher-order functions in this <a target="_blank" href="https://www.freecodecamp.org/news/a-quick-intro-to-higher-order-functions-in-javascript-1a014f89c6b/">article</a></p>
</blockquote>
<p>now, we can create one that returns a promise to resolve all our action methods and catch any possible errors.</p>
<p>here's an example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> req = <span class="hljs-function">(<span class="hljs-params">fn: <span class="hljs-built_in">any</span></span>) =&gt;</span> (req: Request, res: Response, next: NextFunction) =&gt; {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.resolve(fn(req, res, next)).catch(next);
}
</code></pre>
<p>as you can see, this is a middleware that takes a single parameter <code>fn</code>, (which is our action method) and returns a promise.</p>
<p>now we can use this middleware to wrap all our methods:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> express, { NextFunction, Request, Response } <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>;
<span class="hljs-keyword">import</span> cors <span class="hljs-keyword">from</span> <span class="hljs-string">'cors'</span>;
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'fs'</span>;

<span class="hljs-keyword">const</span> app = express();
app.use(cors());

<span class="hljs-comment">// here's our middleware that will check all our methods for us</span>
<span class="hljs-keyword">const</span> req = <span class="hljs-function">(<span class="hljs-params">fn: <span class="hljs-built_in">any</span></span>) =&gt;</span> (req: Request, res: Response, next: NextFunction) =&gt; {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.resolve(fn(req, res, next)).catch(next);
}

<span class="hljs-comment">/**
 * as you can see here, we're calling our middleware and pass 
 * our action method as a parameter
 */</span>
app.post(<span class="hljs-string">'write-test'</span>, req(<span class="hljs-function">(<span class="hljs-params">req: Request, res: Response</span>) =&gt;</span> {
    fs.writeFileSync(<span class="hljs-string">"programming.txt"</span>, undefinedvarible); <span class="hljs-comment">// this code should raise an exception</span>
}));

<span class="hljs-comment">// Last middleware</span>
app.use(<span class="hljs-function">(<span class="hljs-params">err:  <span class="hljs-built_in">Error</span>, req: Request, res: Response, next: NextFunction</span>) =&gt;</span> {
     <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">400</span>).send(<span class="hljs-string">'An error occurred'</span>);
})

app.listen(<span class="hljs-number">5000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Up &amp; Running'</span>));
</code></pre>
<p>here's the result:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1650151204150/T-tffWpGh.png" alt="Screenshot from 2022-04-17 01-18-46.png" /></p>
<p>now our code is much cleaner, and we no longer need to worry about handling errors, this <code>req</code> middleware is going to handle everything for us.</p>
<p>but we still have a little problem here!. as you can see in our result, the result will always be the same. and we can't return the same message for each exception, this doesn't tell us a lot about the exception reason or what we have to change.
as an example let's create <code>404</code> error for not found routes: <code>File: NotfoundError.ts</code></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> NotFoundError <span class="hljs-keyword">extends</span> <span class="hljs-built_in">Error</span>  {
    statusCode = <span class="hljs-number">404</span>; <span class="hljs-comment">// Not found</span>
    message: <span class="hljs-built_in">string</span>;

    <span class="hljs-keyword">constructor</span>(<span class="hljs-params">message: <span class="hljs-built_in">string</span> = 'Not Found'</span>) {
        <span class="hljs-built_in">super</span>();
        <span class="hljs-built_in">this</span>.message = message;
    }
}
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> NotFoundError;
</code></pre>
<p>now we can create a route with wildcard <code>*</code> at the end of our routes to catch all not found routes:</p>
<pre><code class="lang-typescript">app.use(<span class="hljs-string">'*'</span>, <span class="hljs-function">(<span class="hljs-params">req: Request, res: Response, next: NextFunction</span>) =&gt;</span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotFoundError();
});
</code></pre>
<p>as you can see, now we're throwing our custom <code>NotFoundError</code> error, this will give us much more flexibility. but now let's edit our error handler, in order to send the particular message &amp; Status error code  for our exception</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Error Handler</span>
app.use(<span class="hljs-function">(<span class="hljs-params">err:  NotFoundError, req: Request, res: Response, next: NextFunction</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> res.status(error.statusCode).send(err.message);
});
</code></pre>
<p><strong><em>result: </em></strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1650152180929/uBqy4eBrb.png" alt="Screenshot from 2022-04-17 01-35-30.png" /></p>
<p>the response here is much cleaner and tells us what's going on, we also can specify the error code for each kind of error.</p>
<p>as you might notice in our error handler, we still have a little issue that we can't send any other error types, because we define the type of our error to be <code>NotFoundError</code> only, in order to solve this we need to create an abstract class that all of our error classes should inherit from.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> BaseError <span class="hljs-keyword">extends</span> <span class="hljs-built_in">Error</span> {
    <span class="hljs-keyword">abstract</span> statusCode: <span class="hljs-built_in">number</span>;

    <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">public</span> message: <span class="hljs-built_in">string</span> = "An error occurred"</span>) {
        <span class="hljs-built_in">super</span>();
    }
}

<span class="hljs-keyword">class</span> NotFoundError <span class="hljs-keyword">extends</span> BaseError {
    statusCode = <span class="hljs-number">404</span>; <span class="hljs-comment">// Not found</span>
    message: <span class="hljs-built_in">string</span>;

    <span class="hljs-keyword">constructor</span>(<span class="hljs-params">message: <span class="hljs-built_in">string</span> = 'Not Found'</span>) {
        <span class="hljs-built_in">super</span>(message);
        <span class="hljs-built_in">this</span>.message = message;
    }
}
</code></pre>
<p>we should also modify our error handler middleware as follows:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Error Handler</span>
app.use(<span class="hljs-function">(<span class="hljs-params">err:  <span class="hljs-built_in">Error</span>, req: Request, res: Response, next: NextFunction</span>) =&gt;</span> {

    <span class="hljs-comment">/**
     * Here we're checking if the raised error is one of our custom errors,
     * so we can send the particular message &amp; statusCode
     */</span>
    <span class="hljs-keyword">if</span> (err <span class="hljs-keyword">instanceof</span> BaseError) {
        <span class="hljs-keyword">return</span> res.status(error.statusCode).send(error.message);
    }

    <span class="hljs-comment">// Otherwise, we respond with generic response message.</span>
    <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">500</span>).send(<span class="hljs-string">'Something went wrong'</span>);
});
</code></pre>
<h1 id="heading-conclusion">Conclusion</h1>
<p>handling your errors in a smarter way can save you from repeating yourself, and you'll also find yourself more comfortable by using this approach. writing <code>try/catch</code> block in every method was a hassle for me, so I think this way is a time saver.</p>
<p>in the end, I hope this article was useful for you, and you got something out of it.
if you have any questions, feel free to write them in the comments section so we can discuss them furthermore.
you can also reach me on my Twitter account: <a target="_blank" href="https://twitter.com/thefeqy">@thefeqy</a></p>
]]></content:encoded></item><item><title><![CDATA[Use laravel's eloquent traits to avoid code duplication]]></title><description><![CDATA[Consider that you have a particular event that you need to fire in several places, such as deleting the model’s related image after the deletion of the…]]></description><link>https://thefeqy.hashnode.dev/use-laravels-eloquent-traits-to-avoid-code-duplication</link><guid isPermaLink="true">https://thefeqy.hashnode.dev/use-laravels-eloquent-traits-to-avoid-code-duplication</guid><category><![CDATA[Laravel]]></category><category><![CDATA[PHP]]></category><dc:creator><![CDATA[Muhammed ElFeqy]]></dc:creator><pubDate>Tue, 05 Apr 2022 06:11:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649224875645/8Q3Z9rZbS.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>Consider that you have a particular event that you need to fire in several places, such as deleting the model’s related image after the deletion of the model itself.
you may use the same code for posts, products, categories, ..etc.</p>
<pre><code class="lang-php"><span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">destroy</span>(<span class="hljs-params">Post $post</span>) </span>{
    <span class="hljs-comment">// Delete all post images</span>
    $post-&gt;images()-&gt;each(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$image</span>) </span>{
        Storage::delete($image-&gt;path);
        $image-&gt;delete();
    });
    $post-&gt;delete();
    <span class="hljs-comment">// ... Some logic</span>
}
</code></pre>
<p>it would be a headache to take care of this each time you need to delete a model.
so, how we can avoid this?</p>
<hr />
<h1 id="heading-use-eloquent-events">Use Eloquent events</h1>
<p>laravel eloquent ships with several events, it allows you to do a particular task at the exact time you need.</p>
<blockquote>
<p>in our example (delete the model’s related images when the model is deleted).</p>
</blockquote>
<p>you can read more about <a target="_blank" href="https://laravel.com/docs/8.x/eloquent#events">Eloquent events</a> In the laravel official Docs
to reach that, you can use the boot static method in your model :</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?PHP</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">Storage</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Post</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span>
</span>{
    <span class="hljs-keyword">protected</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">boot</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">parent</span>::boot();
        <span class="hljs-built_in">static</span>::deleted(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$post</span>) </span>{
            $post-&gt;images()-&gt;each(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$image</span>) </span>{
                Storage::delete($image-&gt;path);
                $image-&gt;delete();
            });
        });
    }
    <span class="hljs-comment">// .. Some logic</span>
}
</code></pre>
<p>now, you don’t have to do anything while you’re deleting a post (Model). laravel will take care of that by firing an event to delete the images each time you try to delete a post.</p>
<p>Ok!, you’re doing great so far, you are just made your code much cleaner by delegating the image deletion logic into the model itself.</p>
<p>but we still have that code duplication problem right?. every time you want to add the same event (deleting the model’s image), you have to copy the same code in that particular model.</p>
<p>and as you already know, this is bad in software development, you’ll have to edit each model once you have an improvement to this piece of code.</p>
<p>so you should make your code DRY (do not repeat yourself) as much as possible.</p>
<p>here, the Bootable Traits are having our backs.</p>
<h1 id="heading-bootable-traits">Bootable Traits</h1>
<p>you can create a trait that has the same logic and use it wherever you need it.
Just create a static method with a name boot{TraitName} (replace {TraitName} with your actual trait name). it will be executed as a boot() method on your Eloquent model.
here’s an example:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">Storage</span>;


<span class="hljs-keyword">trait</span> DeleteModelImages {
    <span class="hljs-comment">/**
     * the bootable trait should have static
     * method with name boot{TraitName}
     * 
     * <span class="hljs-doctag">@example</span> bootDeleteModelImages()
     */</span>
    <span class="hljs-keyword">protected</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bootDeleteModelImages</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">static</span>::deleted(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$model</span>) </span>{
            $model-&gt;images()-&gt;each(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$image</span>) </span>{
                Storage::delete($image-&gt;path);
                $image-&gt;delete();
            });
        });
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Post</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span>
</span>{
    <span class="hljs-keyword">use</span> <span class="hljs-title">DeleteModelImages</span>;

    <span class="hljs-comment">// .. Some logic</span>
}
</code></pre>
<p>As you can see, we encapsulate the logic of deleting the image in a single <strong>bootable trait</strong>, and now it’s a reusable component. just use the same trait <code>DeleteModelImages</code> with any model you need.</p>
<p>now you can delete any post without worrying about deleting its images, you can leave that for laravel to handle.</p>
<hr />
<blockquote>
<p>You can also follow me on <a target="_blank" href="https://twitter.com/thefeqy">Twitter</a> for more tips.</p>
</blockquote>
]]></content:encoded></item></channel></rss>