<?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[Anik Kumar Nandi]]></title><description><![CDATA[About Me]]></description><link>https://blog.aniknandi.pro</link><generator>RSS for Node</generator><lastBuildDate>Wed, 29 Apr 2026 03:21:37 GMT</lastBuildDate><atom:link href="https://blog.aniknandi.pro/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Is ChatGPT Coming for Blue‑Collar Jobs Too?]]></title><description><![CDATA[Artificial Intelligence (AI) is reshaping industries beyond the traditional office setting, making its way into factories, construction sites, and service sectors. This evolution prompts critical questions about the future of work: Which jobs are mos...]]></description><link>https://blog.aniknandi.pro/is-chatgpt-coming-for-bluecollar-jobs-too</link><guid isPermaLink="true">https://blog.aniknandi.pro/is-chatgpt-coming-for-bluecollar-jobs-too</guid><category><![CDATA[ai replace]]></category><category><![CDATA[2Articles1Week]]></category><category><![CDATA[AI]]></category><category><![CDATA[chatgpt]]></category><category><![CDATA[gpt]]></category><category><![CDATA[AI Jobs Platform]]></category><category><![CDATA[#bluecollarjobs #highpayingbluecollarjobs #bluecollarhiring]]></category><dc:creator><![CDATA[Anik Kumar Nandi]]></dc:creator><pubDate>Thu, 16 Oct 2025 04:12:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1760587737768/42e36784-9890-435f-9343-cd8ed3e2a0b0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Artificial Intelligence (AI) is reshaping industries beyond the traditional office setting, making its way into factories, construction sites, and service sectors. This evolution prompts critical questions about the future of work: Which jobs are most susceptible to automation, and how can workers and employers prepare for these changes?</p>
<hr />
<h3 id="heading-how-ai-is-enhancing-blue-collar-work">How AI Is Enhancing Blue-Collar Work</h3>
<p>AI is not merely a replacement for human labor. it is becoming a powerful tool that enhances the capabilities of blue-collar workers. Here's how:</p>
<ul>
<li><p><strong>Predictive Maintenance</strong>: AI systems can analyze data from machinery to predict failures before they occur, allowing for timely maintenance and reducing downtime.</p>
</li>
<li><p><strong>Inventory and Supply Chain Optimization</strong>: AI algorithms can forecast demand, manage inventory levels, and streamline supply chains, ensuring that materials are available when needed without overstocking.</p>
</li>
<li><p><strong>Training and Skill Development</strong>: Virtual reality (VR) and augmented reality (AR) powered by AI are being used to train workers in complex tasks, providing immersive learning experiences without the risks associated with on-the-job training.</p>
</li>
<li><p><strong>Safety Enhancements</strong>: AI-driven sensors and monitoring systems can detect hazardous conditions in real-time, alerting workers and supervisors to potential dangers, thereby reducing workplace accidents.</p>
</li>
</ul>
<hr />
<h3 id="heading-jobs-most-at-risk">Jobs Most at Risk</h3>
<p>While AI offers numerous benefits, certain roles are more vulnerable to automation:</p>
<ul>
<li><p><strong>Repetitive Manual Tasks</strong>: Jobs involving routine physical labor, such as assembly line work, are susceptible to being replaced by robotic systems.</p>
</li>
<li><p><strong>Data-Intensive Roles</strong>: Positions that involve processing large amounts of data, like inventory tracking or basic quality control, can be automated using AI tools.</p>
</li>
<li><p><strong>Hybrid Roles</strong>: Jobs that combine manual labor with decision-making, such as machine operators, may see their tasks divided between human workers and AI systems.</p>
</li>
</ul>
<p>It's important to note that the impact of AI adoption varies across regions. Wealthier countries may experience faster integration of AI technologies, potentially leading to quicker displacement in certain sectors.</p>
<hr />
<h3 id="heading-balancing-the-pros-and-cons">Balancing the Pros and Cons</h3>
<p><strong>Potential Risks</strong>:</p>
<ul>
<li><p><strong>Job Displacement</strong>: Automation could lead to the reduction or elimination of certain job categories.</p>
</li>
<li><p><strong>Wage Pressure</strong>: An oversupply of labor in certain sectors due to job losses may drive wages down.</p>
</li>
<li><p><strong>Skill Gaps</strong>: Workers may need to acquire new skills to remain competitive in the evolving job market.</p>
</li>
<li><p><strong>Economic Inequality</strong>: If the benefits of AI are not equitably distributed, there could be a widening gap between high-skill, high-wage workers and those in lower-skill, lower-wage roles.</p>
</li>
</ul>
<p><strong>Emerging Opportunities</strong>:</p>
<ul>
<li><p><strong>Increased Productivity</strong>: AI can handle repetitive tasks, allowing human workers to focus on more complex and creative aspects of their jobs.</p>
</li>
<li><p><strong>New Job Categories</strong>: Roles such as AI maintenance specialists, data analysts, and human-AI interaction designers are emerging.</p>
</li>
<li><p><strong>Enhanced Collaboration</strong>: AI can serve as a collaborative tool, augmenting human capabilities rather than replacing them.</p>
</li>
</ul>
<hr />
<h3 id="heading-preparing-for-the-ai-driven-future">Preparing for the AI-Driven Future</h3>
<p><strong>For Workers</strong>:</p>
<ul>
<li><p><strong>Continuous Learning</strong>: Engage in lifelong learning to acquire new skills, particularly in areas like data analysis, machine learning, and digital literacy.</p>
</li>
<li><p><strong>Adaptability</strong>: Cultivate the ability to adapt to new technologies and workflows.</p>
</li>
<li><p><strong>Soft Skills</strong>: Emphasize interpersonal skills, problem-solving, and creativity, which are less likely to be automated.</p>
</li>
</ul>
<p><strong>For Employers</strong>:</p>
<ul>
<li><p><strong>Invest in Training</strong>: Provide opportunities for employees to upskill and reskill in response to technological advancements.</p>
</li>
<li><p><strong>Human-AI Collaboration</strong>: Design workflows that leverage both human expertise and AI efficiency.</p>
</li>
<li><p><strong>Ethical Implementation</strong>: Ensure that AI systems are implemented transparently and ethically, with consideration for their impact on the workforce.</p>
</li>
</ul>
<p><strong>For Policymakers</strong>:</p>
<ul>
<li><p><strong>Regulatory Frameworks</strong>: Develop policies that govern the ethical use of AI, protecting workers' rights and promoting fair labor practices.</p>
</li>
<li><p><strong>Support Systems</strong>: Establish safety nets, such as unemployment benefits and retraining programs, to assist workers displaced by automation.</p>
</li>
<li><p><strong>Inclusive Decision-Making</strong>: Involve workers, unions, and communities in discussions about AI implementation to ensure that diverse perspectives are considered.</p>
</li>
</ul>
<hr />
<h3 id="heading-envisioning-the-future">Envisioning the Future</h3>
<p>The integration of AI into blue-collar industries is already underway and will continue to evolve. In the future, we might see:</p>
<ul>
<li><p><strong>AI-Assisted Diagnostics</strong>: Workers using AI tools to identify issues in machinery or infrastructure more efficiently.</p>
</li>
<li><p><strong>Robotic Exoskeletons</strong>: Wearable devices powered by AI that assist workers in lifting heavy objects, reducing physical strain.</p>
</li>
<li><p><strong>Smart Construction Sites</strong>: AI systems managing construction projects, optimizing schedules, and ensuring safety compliance.</p>
</li>
<li><p><strong>Personalized Training Programs</strong>: AI-driven platforms offering customized learning experiences to workers based on their individual needs and progress.</p>
</li>
</ul>
<p>While the transition may present challenges, it also holds the potential to create a more dynamic and resilient workforce. By embracing AI as a tool for enhancement rather than a force of replacement, workers, employers, and policymakers can navigate the future of work together.</p>
]]></content:encoded></item><item><title><![CDATA[Optimizing Laravel Performance: Tips for Faster APIs]]></title><description><![CDATA[1. Cache Your Routes for Faster Request Handling
What It Means:
When Laravel processes a request, it goes through all the route files to find a match. This can take a bit of time, especially as your number of routes increases.
The Solution:
Utilize r...]]></description><link>https://blog.aniknandi.pro/optimizing-laravel-performance-tips-for-faster-apis</link><guid isPermaLink="true">https://blog.aniknandi.pro/optimizing-laravel-performance-tips-for-faster-apis</guid><category><![CDATA[Laravel]]></category><category><![CDATA[PHP]]></category><category><![CDATA[optimization]]></category><category><![CDATA[good practices]]></category><category><![CDATA[query-optimization]]></category><category><![CDATA[programing]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Anik Kumar Nandi]]></dc:creator><pubDate>Fri, 18 Apr 2025 18:18:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1744999937846/4b2b1b7f-3343-400e-993f-ffd7f865bbc9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-1-cache-your-routes-for-faster-request-handling">1. Cache Your Routes for Faster Request Handling</h2>
<h3 id="heading-what-it-means">What It Means:</h3>
<p>When Laravel processes a request, it goes through all the route files to find a match. This can take a bit of time, especially as your number of routes increases.</p>
<h3 id="heading-the-solution">The Solution:</h3>
<p>Utilize <strong>route caching</strong> to compile all your routes into a single file.</p>
<h3 id="heading-how-to-do-it">How to Do It:</h3>
<pre><code class="lang-bash">php artisan route:cache
</code></pre>
<p>This command will generate a cached routes file, which Laravel can read much faster.</p>
<h3 id="heading-to-clear-the-cache">To Clear the Cache:</h3>
<pre><code class="lang-bash">php artisan route:clear
</code></pre>
<p><strong>Tip:</strong> Only use this in <strong>production</strong>. During development, cached routes may hide updates.</p>
<hr />
<h2 id="heading-2-optimize-your-database-queries">2. Optimize Your Database Queries</h2>
<h3 id="heading-problem">Problem:</h3>
<p>Most slow APIs happen because of inefficient or unnecessary database queries.</p>
<h3 id="heading-best-practices">Best Practices:</h3>
<h4 id="heading-a-use-eager-loading-to-avoid-n1-queries">a. Use Eager Loading to Avoid N+1 Queries</h4>
<p><strong>Bad Example (Lazy Loading):</strong></p>
<pre><code class="lang-php">$users = User::all();

<span class="hljs-keyword">foreach</span> ($users <span class="hljs-keyword">as</span> $user) {
    <span class="hljs-keyword">echo</span> $user-&gt;posts-&gt;count(); <span class="hljs-comment">// Triggers a new query each time</span>
}
</code></pre>
<p><strong>Better Example (Eager Loading):</strong></p>
<pre><code class="lang-php">$users = User::with(<span class="hljs-string">'posts'</span>)-&gt;get();

<span class="hljs-keyword">foreach</span> ($users <span class="hljs-keyword">as</span> $user) {
    <span class="hljs-keyword">echo</span> $user-&gt;posts-&gt;count(); <span class="hljs-comment">// already-loaded posts data</span>
}
</code></pre>
<p>This reduces the number of queries and boosts performance significantly.</p>
<hr />
<h4 id="heading-b-avoid-unnecessary-queries">b. Avoid Unnecessary Queries</h4>
<p>Instead of this:</p>
<pre><code class="lang-php">$user = User::where(<span class="hljs-string">'email'</span>, <span class="hljs-string">'test@example.com'</span>)-&gt;first();
</code></pre>
<p>Do this:</p>
<pre><code class="lang-php">$user = User::firstWhere(<span class="hljs-string">'email'</span>, <span class="hljs-string">'test@example.com'</span>);
</code></pre>
<p>Both do the same thing, but the second one is shorter and cleaner.</p>
<hr />
<h4 id="heading-c-use-select-to-limit-returned-columns">c. Use <code>select()</code> to Limit Returned Columns</h4>
<p>If you don’t need all columns, don’t fetch them:</p>
<pre><code class="lang-php">$users = User::select(<span class="hljs-string">'id'</span>, <span class="hljs-string">'name'</span>)-&gt;get();
</code></pre>
<p>This reduces payload size and improves query speed.</p>
<hr />
<h2 id="heading-3-remove-unused-services-and-middleware">3. Remove Unused Services and Middleware</h2>
<h3 id="heading-why-it-matters">Why It Matters:</h3>
<p>Each request runs through all registered middleware. Extra or unused middleware slows down your app.</p>
<h3 id="heading-what-you-can-do">What You Can Do:</h3>
<ul>
<li><p>Review <code>app/Http/Kernel.php</code> and remove any middleware you don’t need.</p>
</li>
<li><p>Disable unnecessary service providers in <code>config/app.php</code>.</p>
</li>
</ul>
<hr />
<h2 id="heading-4-use-laravels-caching-system-wisely">4. Use Laravel’s Caching System Wisely</h2>
<p>Laravel supports caching via file, Redis, Memcached, and database drivers.</p>
<h3 id="heading-a-cache-configuration-files">a. Cache Configuration Files</h3>
<pre><code class="lang-bash">php artisan config:cache
</code></pre>
<p>Laravel combines all config files into one file for faster loading.</p>
<hr />
<h3 id="heading-b-cache-views">b. Cache Views</h3>
<pre><code class="lang-bash">php artisan view:cache
</code></pre>
<p>This compiles Blade templates into PHP and speeds up rendering.</p>
<hr />
<h3 id="heading-c-cache-expensive-queries">c. Cache Expensive Queries</h3>
<pre><code class="lang-php">$posts = Cache::remember(<span class="hljs-string">'popular_posts'</span>, now()-&gt;addMinutes(<span class="hljs-number">10</span>), <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> Post::orderBy(<span class="hljs-string">'views'</span>, <span class="hljs-string">'desc'</span>)-&gt;take(<span class="hljs-number">5</span>)-&gt;get();
});
</code></pre>
<p>This avoids running the same query over and over again.</p>
<hr />
<h2 id="heading-5-use-queues-for-time-consuming-tasks">5. Use Queues for Time-Consuming Tasks</h2>
<h3 id="heading-why">Why:</h3>
<p>If you’re doing things like sending emails, uploading files, or generating PDFs directly in your API, your response will be slow.</p>
<h3 id="heading-use-laravel-queues">Use Laravel Queues:</h3>
<p><strong>Step 1: Create a Job</strong></p>
<pre><code class="lang-bash">php artisan make:job SendWelcomeEmail
</code></pre>
<p><strong>Step 2: Dispatch the Job</strong></p>
<pre><code class="lang-php">SendWelcomeEmail::dispatch($user);
</code></pre>
<p><strong>Step 3: Run the Queue Worker</strong></p>
<pre><code class="lang-bash">php artisan queue:work
</code></pre>
<p>This sends the email in the background, while your API returns a fast response.</p>
<hr />
<h2 id="heading-6-paginate-large-datasets">6. Paginate Large Datasets</h2>
<h3 id="heading-bad-returning-too-much-data">Bad: Returning Too Much Data</h3>
<pre><code class="lang-php"><span class="hljs-keyword">return</span> User::all(); <span class="hljs-comment">// May return thousands of records</span>
</code></pre>
<h3 id="heading-good-use-pagination">Good: Use Pagination</h3>
<pre><code class="lang-php"><span class="hljs-keyword">return</span> User::paginate(<span class="hljs-number">20</span>); <span class="hljs-comment">// Returns 20 records per page</span>
</code></pre>
<p>You can also use:</p>
<pre><code class="lang-php"><span class="hljs-keyword">return</span> User::simplePaginate(<span class="hljs-number">20</span>); <span class="hljs-comment">// Lighter version without total page count</span>
</code></pre>
<hr />
<h2 id="heading-7-clean-and-minimize-json-responses-with-laravel-api-resources">7. Clean and Minimize JSON Responses (with Laravel API Resources)</h2>
<p>When building APIs, returning the entire model data is <strong>not a good idea</strong>, it exposes unnecessary fields (like passwords, timestamps, etc.) and makes your response payload heavier.</p>
<h3 id="heading-the-solution-use-laravels-api-resources">The Solution: Use Laravel’s API Resources</h3>
<p>Laravel provides <strong>Resource Classes</strong> to control how your models are converted to JSON responses. You get <strong>cleaner, lighter, and safer</strong> outputs.</p>
<h3 id="heading-step-by-step-how-to-create-and-use-laravel-api-resources">Step-by-Step: How to Create and Use Laravel API Resources</h3>
<hr />
<h3 id="heading-step-1-generate-a-resource-class">Step 1: Generate a Resource Class</h3>
<p>Run this Artisan command to generate a resource:</p>
<pre><code class="lang-bash">php artisan make:resource UserResource
</code></pre>
<p>This will create a file:</p>
<pre><code class="lang-bash">app/Http/Resources/UserResource.php
</code></pre>
<h3 id="heading-step-2-define-the-data-you-want-to-return">Step 2: Define the Data You Want to Return</h3>
<p>Open <code>UserResource.php</code> and customize the <code>toArray()</code> method:</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">Http</span>\<span class="hljs-title">Resources</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Request</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Resources</span>\<span class="hljs-title">Json</span>\<span class="hljs-title">JsonResource</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserResource</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">JsonResource</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">toArray</span>(<span class="hljs-params">Request $request</span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'id'</span>    =&gt; <span class="hljs-keyword">$this</span>-&gt;id,
            <span class="hljs-string">'name'</span>  =&gt; <span class="hljs-keyword">$this</span>-&gt;name,
            <span class="hljs-string">'email'</span> =&gt; <span class="hljs-keyword">$this</span>-&gt;email,
            <span class="hljs-string">'joined'</span> =&gt; <span class="hljs-keyword">$this</span>-&gt;created_at-&gt;format(<span class="hljs-string">'Y-m-d'</span>),
        ];
    }
}
</code></pre>
<p>Only the selected fields will be returned in the API response.</p>
<hr />
<h3 id="heading-step-3-use-the-resource-in-your-controller">Step 3: Use the Resource in Your Controller</h3>
<p>Instead of returning the full model:</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">Http</span>\<span class="hljs-title">Controllers</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserController</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">show</span>(<span class="hljs-params">$id</span>)
    </span>{
        <span class="hljs-keyword">return</span> User::find($id);
    }
}
</code></pre>
<p>Use the resource:</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">Http</span>\<span class="hljs-title">Controllers</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Resources</span>\<span class="hljs-title">UserResource</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserController</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">show</span>(<span class="hljs-params">$id</span>)
    </span>{
        <span class="hljs-keyword">return</span> response()-&gt;json([
                <span class="hljs-string">'success'</span> =&gt; <span class="hljs-literal">true</span>,
                <span class="hljs-string">'message'</span> =&gt; <span class="hljs-string">'User data successfully fetched'</span>,
                <span class="hljs-string">'data'</span> =&gt;  UserResource::make(User::find($id)),
            ], <span class="hljs-number">200</span>);    
    }
}
</code></pre>
<h3 id="heading-for-collections-multiple-users">For Collections (Multiple Users):</h3>
<p>If you’re returning a list of users, use:</p>
<pre><code class="lang-php">UserResource::collection(User::all())
</code></pre>
<p>Make sure you eager load the relation in the controller:</p>
<pre><code class="lang-php">$user = User::with(<span class="hljs-string">'posts'</span>)-&gt;find($id);
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> UserResource($user);
</code></pre>
<hr />
<h3 id="heading-avoid-this">Avoid This:</h3>
<pre><code class="lang-php"><span class="hljs-keyword">return</span> response()-&gt;json($user); <span class="hljs-comment">// Dumps the whole model, including sensitive data</span>
</code></pre>
<p>Instead, always use a <strong>Resource class</strong> to protect and control your API output.</p>
<hr />
<h3 id="heading-tip-hide-attributes-with-this-gtmergewhen">💡 Tip: Hide Attributes with <code>$this-&gt;mergeWhen</code></h3>
<p>Return values only when certain conditions are met:</p>
<pre><code class="lang-php"><span class="hljs-keyword">return</span> [
    <span class="hljs-string">'id'</span> =&gt; <span class="hljs-keyword">$this</span>-&gt;id,
    <span class="hljs-string">'email'</span> =&gt; <span class="hljs-keyword">$this</span>-&gt;when(auth()-&gt;user()-&gt;isAdmin(), <span class="hljs-keyword">$this</span>-&gt;email),
];
</code></pre>
<hr />
<h2 id="heading-8-use-redis-for-cache-and-queues">8. Use Redis for Cache and Queues</h2>
<p>Redis is fast and efficient for handling cache, session, and queue data.</p>
<h3 id="heading-install-redis-and-update-env">Install Redis and Update <code>.env</code></h3>
<pre><code class="lang-php">CACHE_DRIVER=redis
QUEUE_CONNECTION=redis
SESSION_DRIVER=redis
</code></pre>
<p>Install the PHP Redis extension via:</p>
<pre><code class="lang-bash">sudo apt install php-redis
</code></pre>
<p>Or using Composer:</p>
<pre><code class="lang-bash">composer require predis/predis
</code></pre>
<hr />
<h2 id="heading-9-use-debug-tools-in-development">9. Use Debug Tools in Development</h2>
<h3 id="heading-use-laravel-debugbar">Use Laravel Debugbar</h3>
<pre><code class="lang-bash">composer require barryvdh/laravel-debugbar --dev
</code></pre>
<p>This shows you:</p>
<ul>
<li><p>Total execution time</p>
</li>
<li><p>Number of queries</p>
</li>
<li><p>Memory usage</p>
</li>
<li><p>Request details</p>
</li>
</ul>
<h3 id="heading-use-laravel-telescope">Use Laravel Telescope</h3>
<pre><code class="lang-bash">composer require laravel/telescope --dev
php artisan telescope:install
php artisan migrate
</code></pre>
<p>Telescope is like a mini control panel to inspect requests, jobs, DB queries, and more.</p>
<p>❗ Don’t use these in production, they can slow things down.</p>
<hr />
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>You don’t need to be an expert to start optimizing your Laravel APIs. Just take small steps:</p>
<ul>
<li><p>Cache where possible</p>
</li>
<li><p>Query smartly</p>
</li>
<li><p>Avoid doing too much in one request</p>
</li>
</ul>
<p>Over time, these best practices will make your app <strong>faster, more scalable, and more professional</strong>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Optimizing Laravel API performance does not have to be complex. it is about consistently applying the appropriate practices.</p>
<p>By caching routes, reducing database load, minimizing JSON responses, and offloading heavy tasks to queues, you can <strong>greatly enhance the speed, scalability, and reliability</strong> of your Laravel APIs.</p>
<p>Leveraging Laravel’s powerful tools like Eager Loading, API Resources, and built-in caching gives you <strong>detailed control</strong> over your app’s performance without making things too complex.</p>
<p>Start small, focus on optimizing one part at a time, and soon your APIs will be faster, cleaner, and ready to handle production-level traffic. 🚀</p>
]]></content:encoded></item><item><title><![CDATA[Good Code vs. Bad Code: Understanding the Difference and Their Impact]]></title><description><![CDATA[Introduction
In software development, the difference between good code and bad code can make or break a project. Good code ensures maintainability, scalability, and efficiency, while bad code can lead to technical debt, higher development costs, and ...]]></description><link>https://blog.aniknandi.pro/good-code-vs-bad-code-understanding-the-difference-and-their-impact</link><guid isPermaLink="true">https://blog.aniknandi.pro/good-code-vs-bad-code-understanding-the-difference-and-their-impact</guid><category><![CDATA[good code vs bad code]]></category><category><![CDATA[good code]]></category><category><![CDATA[bad code]]></category><category><![CDATA[Bugs and Errors]]></category><category><![CDATA[programing]]></category><category><![CDATA[PHP]]></category><category><![CDATA[Laravel]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Anik Kumar Nandi]]></dc:creator><pubDate>Mon, 24 Mar 2025 15:05:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1742828462422/d5b91e4d-ea35-4a3a-bc89-6ec7e5970f0c.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In software development, the difference between good code and bad code can make or break a project. Good code ensures maintainability, scalability, and efficiency, while bad code can lead to technical debt, higher development costs, and frustration for both developers and users. In this blog, we will explore the key differences between good and bad code, their pros and cons, and best practices for writing better code.</p>
<h2 id="heading-what-is-good-code">What is Good Code?</h2>
<p>Good code is well-structured, easy to read, and maintainable. It follows best coding practices and maintains a consistent style. Here are some key characteristics of good code:</p>
<h3 id="heading-characteristics-of-good-code">Characteristics of Good Code</h3>
<ol>
<li><p><strong>Readability</strong> – Good code is easy to read and understand.</p>
</li>
<li><p><strong>Maintainability</strong> – It is easy to modify and extend.</p>
</li>
<li><p><strong>Scalability</strong> – It can handle growth and increased workload efficiently.</p>
</li>
<li><p><strong>Reusability</strong> – Good code is modular and can be reused in different parts of the application.</p>
</li>
<li><p><strong>Performance Optimization</strong> – It runs efficiently without unnecessary processing overhead.</p>
</li>
<li><p><strong>Error Handling</strong> – It includes proper exception handling to prevent crashes and unexpected behavior.</p>
</li>
<li><p><strong>Consistency</strong> – Follows a uniform coding style and best practices.</p>
</li>
<li><p><strong>Minimal Complexity</strong> – Avoids unnecessary complexity and keeps the logic simple.</p>
</li>
</ol>
<h3 id="heading-example-of-good-code-in-php">Example of Good Code in PHP</h3>
<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">string</span> $name;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> $email;

    <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">string</span> $name, <span class="hljs-keyword">string</span> $email</span>) </span>{
        <span class="hljs-keyword">$this</span>-&gt;name = $name;
        <span class="hljs-keyword">$this</span>-&gt;email = $email;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getName</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;name;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getEmail</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;email;
    }
}
</code></pre>
<p>This code is readable, structured, and follows object-oriented principles, making it easy to maintain and extend.</p>
<h3 id="heading-example-of-good-code-in-laravel">Example of Good Code in Laravel</h3>
<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">User</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">Log</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserController</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">getUserByEmail</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $email</span>) </span>{
        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">return</span> User::where(<span class="hljs-string">'email'</span>, $email)-&gt;firstOrFail();
        } <span class="hljs-keyword">catch</span> (ModelNotFoundException $e) {
            Log::error(<span class="hljs-string">"User not found: "</span> . $email);
            <span class="hljs-keyword">return</span> response()-&gt;json([<span class="hljs-string">'error'</span> =&gt; <span class="hljs-string">'User not found'</span>], <span class="hljs-number">404</span>);
        }
    }
}
</code></pre>
<p>This Laravel code follows best practices by using Eloquent ORM, handling exceptions, and logging errors properly.</p>
<h3 id="heading-example-of-good-code-in-javascript">Example of Good Code in JavaScript</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params">url</span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">let</span> response = <span class="hljs-keyword">await</span> fetch(url);
        <span class="hljs-keyword">if</span> (!response.ok) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Network response was not ok'</span>);
        }
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> response.json();
    } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Fetch error:'</span>, error);
    }
}
</code></pre>
<p>This JavaScript function is well-structured, includes proper error handling, and follows best practices for asynchronous programming.</p>
<h3 id="heading-example-of-good-code-in-mysql">Example of Good Code in MySQL</h3>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> <span class="hljs-keyword">users</span> (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">INT</span> AUTO_INCREMENT PRIMARY <span class="hljs-keyword">KEY</span>,
    <span class="hljs-keyword">name</span> <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">100</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    email <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">255</span>) <span class="hljs-keyword">UNIQUE</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    created_at <span class="hljs-built_in">TIMESTAMP</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span>
);

<span class="hljs-comment">-- Using parameterized queries to prevent SQL injection</span>
<span class="hljs-keyword">PREPARE</span> stmt <span class="hljs-keyword">FROM</span> <span class="hljs-string">'SELECT * FROM users WHERE email = ?'</span>;
<span class="hljs-keyword">SET</span> @email = <span class="hljs-string">'user@example.com'</span>;
<span class="hljs-keyword">EXECUTE</span> stmt <span class="hljs-keyword">USING</span> @email;
</code></pre>
<p>This MySQL code creates a well-structured <code>users</code> table and uses a parameterized query to prevent SQL injection, improving security and efficiency.</p>
<h2 id="heading-what-is-bad-code">What is Bad Code?</h2>
<p>Bad code is hard to understand, difficult to maintain, and often causes bugs and performance problems. It is typically written without following best practices.</p>
<h3 id="heading-characteristics-of-bad-code">Characteristics of Bad Code</h3>
<ol>
<li><p><strong>Lack of Readability</strong> – Difficult to read and understand.</p>
</li>
<li><p><strong>Poor Maintainability</strong> – Hard to update and fix bugs.</p>
</li>
<li><p><strong>Performance Issues</strong> – Inefficient code that slows down execution.</p>
</li>
<li><p><strong>No Error Handling</strong> – Leads to unexpected crashes.</p>
</li>
<li><p><strong>Inconsistent Coding Style</strong> – Uses different conventions across the codebase.</p>
</li>
<li><p><strong>Too Many Hardcoded Values</strong> – Reduces flexibility and increases maintenance overhead.</p>
</li>
<li><p><strong>Code Duplication</strong> – Repeated code instead of using functions or reusable components.</p>
</li>
<li><p><strong>Lack of Documentation</strong> – No comments or explanations, making it harder for others to understand.</p>
</li>
</ol>
<h3 id="heading-example-of-bad-code-in-php">Example of Bad Code in PHP</h3>
<pre><code class="lang-php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUser</span>(<span class="hljs-params"></span>) </span>{
    $conn = <span class="hljs-keyword">new</span> mysqli(<span class="hljs-string">"localhost"</span>, <span class="hljs-string">"root"</span>, <span class="hljs-string">""</span>, <span class="hljs-string">"users_db"</span>);
    $result = $conn-&gt;query(<span class="hljs-string">"SELECT * FROM users"</span>);
    <span class="hljs-keyword">while</span> ($row = $result-&gt;fetch_assoc()) {
        <span class="hljs-keyword">echo</span> $row[<span class="hljs-string">"name"</span>] . <span class="hljs-string">" - "</span> . $row[<span class="hljs-string">"email"</span>] . <span class="hljs-string">"&lt;br&gt;"</span>;
    }
    $conn-&gt;close();
}
</code></pre>
<h4 id="heading-problems-with-this-code">Problems with this Code:</h4>
<ul>
<li><p><strong>No Error Handling</strong> – If the database connection fails, it will cause issues.</p>
</li>
<li><p><strong>No Prepared Statements</strong> – Vulnerable to SQL injection attacks.</p>
</li>
<li><p><strong>Hardcoded Database Credentials</strong> – A security risk.</p>
</li>
<li><p><strong>Mixing Logic with Output</strong> – Should separate logic from presentation.</p>
</li>
</ul>
<h3 id="heading-example-of-bad-code-in-laravel">Example of Bad Code in Laravel</h3>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserController</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">getUserByEmail</span>(<span class="hljs-params">$email</span>) </span>{
        $user = DB::select(<span class="hljs-string">"SELECT * FROM users WHERE email = '<span class="hljs-subst">$email</span>'"</span>);
        <span class="hljs-keyword">if</span> (!$user) {
            <span class="hljs-keyword">return</span> <span class="hljs-string">"User not found"</span>;
        }
        <span class="hljs-keyword">return</span> $user;
    }
}
</code></pre>
<h4 id="heading-problems-with-this-code-1">Problems with this Code:</h4>
<ul>
<li><p><strong>SQL Injection Risk</strong> – Using raw SQL queries with user input is dangerous.</p>
</li>
<li><p><strong>No Exception Handling</strong> – If the query fails, the function breaks.</p>
</li>
<li><p><strong>Inconsistent Response</strong> – Returns a string instead of a structured JSON response.</p>
</li>
<li><p><strong>No Logging</strong> – Errors are not logged, making debugging harder.</p>
</li>
</ul>
<h3 id="heading-example-of-bad-code-in-javascript">Example of Bad Code in JavaScript</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params">url</span>) </span>{
    fetch(url)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
    .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
    .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> alert(<span class="hljs-string">"Something went wrong"</span>));
}
</code></pre>
<h4 id="heading-problems-with-this-code-2">Problems with this Code:</h4>
<ul>
<li><p><strong>No Proper Error Handling</strong> – Only shows a generic alert instead of logging useful information.</p>
</li>
<li><p><strong>Lack of Response Validation</strong> – Assumes the response will always be in JSON format without checking for errors.</p>
</li>
<li><p><strong>No Return Value</strong> – Does not return a promise, limiting reusability.</p>
</li>
</ul>
<h3 id="heading-example-of-bad-code-in-mysql">Example of Bad Code in MySQL</h3>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span> <span class="hljs-keyword">WHERE</span> email = <span class="hljs-string">'user@example.com'</span>;
</code></pre>
<h4 id="heading-problems-with-this-code-3">Problems with this Code:</h4>
<ul>
<li><p><strong>Vulnerable to SQL Injection</strong> – If user input is concatenated, it can be exploited.</p>
</li>
<li><p><strong>No Indexing</strong> – Could lead to slow query performance in large databases.</p>
</li>
<li><p><strong>No Parameterization</strong> – Should use prepared statements for security.</p>
</li>
</ul>
<h2 id="heading-impact-of-good-code-vs-bad-code">Impact of Good Code vs. Bad Code</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Factor</strong></td><td><strong>Good Code</strong></td><td><strong>Bad Code</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Performance</strong></td><td>Optimized and efficient</td><td>Slow and inefficient</td></tr>
<tr>
<td><strong>Maintainability</strong></td><td>Easy to modify and extend</td><td>Difficult to update and debug</td></tr>
<tr>
<td><strong>Security</strong></td><td>Follows best security practices</td><td>Prone to vulnerabilities</td></tr>
<tr>
<td><strong>Scalability</strong></td><td>Can handle future growth</td><td>Struggles with increased load</td></tr>
<tr>
<td><strong>Collaboration</strong></td><td>Easy for teams to understand and work with</td><td>Confusing and frustrating for developers</td></tr>
</tbody>
</table>
</div><h2 id="heading-best-practices-to-write-good-code">Best Practices to Write Good Code</h2>
<ol>
<li><p><strong>Follow Coding Standards</strong> – Use industry-standard guidelines such as PSR for PHP.</p>
</li>
<li><p><strong>Write Modular Code</strong> – Break down large functions into smaller, reusable components.</p>
</li>
<li><p><strong>Use Meaningful Names</strong> – Variable and function names should be descriptive.</p>
</li>
<li><p><strong>Implement Proper Error Handling</strong> – Use try-catch blocks and meaningful error messages.</p>
</li>
<li><p><strong>Use Version Control</strong> – Maintain code history using Git.</p>
</li>
<li><p><strong>Write Unit Tests</strong> – Ensure your code works as expected.</p>
</li>
<li><p><strong>Avoid Code Duplication</strong> – Use functions or classes instead of repeating code.</p>
</li>
<li><p><strong>Write Documentation</strong> – Add comments and document your codebase for clarity.</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Good code is the foundation of a successful software project, ensuring efficiency, security, and easy maintenance. Bad code, however, results in technical debt, security risks, and higher development costs. By following best practices and prioritizing code quality, developers can build strong and scalable applications that last over time.</p>
]]></content:encoded></item><item><title><![CDATA[How to Build a Progressive Web App (PWA) from Scratch for HTML, CSS, and JavaScript Website]]></title><description><![CDATA[Progressive Web Apps (PWAs) are web applications that provide a native app-like experience to users. They work offline, load faster, and can be installed on devices, making them a great choice for modern web development. If you have a website built w...]]></description><link>https://blog.aniknandi.pro/how-to-build-a-progressive-web-app-pwa-from-scratch-with-html-css-and-javascript</link><guid isPermaLink="true">https://blog.aniknandi.pro/how-to-build-a-progressive-web-app-pwa-from-scratch-with-html-css-and-javascript</guid><category><![CDATA[PWA]]></category><category><![CDATA[PWAs]]></category><category><![CDATA[progressive web app]]></category><category><![CDATA[pwa web app development,]]></category><category><![CDATA[pwa development services]]></category><dc:creator><![CDATA[Anik Kumar Nandi]]></dc:creator><pubDate>Wed, 01 Jan 2025 18:25:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1735755976280/77bb74d8-cab8-46bc-9c61-79ef9e11f52e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Progressive Web Apps (PWAs) are web applications that provide a native app-like experience to users. They work offline, load faster, and can be installed on devices, making them a great choice for modern web development. If you have a website built with HTML, CSS, and JavaScript, you can transform it into a PWA with a few simple steps. In this blog, we’ll walk you through the process.</p>
<h2 id="heading-step-1-understand-the-core-components-of-a-pwa">Step 1: Understand the Core Components of a PWA</h2>
<p>To create a PWA, you need the following:</p>
<ol>
<li><p><strong>A Secure Website</strong>: Your website must be served over HTTPS.</p>
</li>
<li><p><strong>A Web App Manifest</strong>: This JSON file provides metadata about your PWA.</p>
</li>
<li><p><strong>A Service Worker</strong>: A script that runs in the background and manages caching and offline functionality.</p>
</li>
<li><p><strong>Responsive Design</strong>: Ensure your website is mobile-friendly.</p>
</li>
</ol>
<hr />
<h2 id="heading-step-2-create-a-web-app-manifest">Step 2: Create a Web App Manifest</h2>
<p>The manifest file contains essential information about your app, such as its name, icons, and display mode. Create a file named <code>manifest.json</code> in your project directory and add the following:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"My PWA App"</span>,
  <span class="hljs-attr">"short_name"</span>: <span class="hljs-string">"PWA"</span>,
  <span class="hljs-attr">"start_url"</span>: <span class="hljs-string">"/index.html"</span>,
  <span class="hljs-attr">"display"</span>: <span class="hljs-string">"standalone"</span>,
  <span class="hljs-attr">"background_color"</span>: <span class="hljs-string">"#ffffff"</span>,
  <span class="hljs-attr">"theme_color"</span>: <span class="hljs-string">"#000000"</span>,
  <span class="hljs-attr">"icons"</span>: [
    {
      <span class="hljs-attr">"src"</span>: <span class="hljs-string">"icons/icon-192x192.png"</span>,
      <span class="hljs-attr">"sizes"</span>: <span class="hljs-string">"192x192"</span>,
      <span class="hljs-attr">"type"</span>: <span class="hljs-string">"image/png"</span>
    },
  ]
}
</code></pre>
<p>Link this file in your HTML:</p>
<pre><code class="lang-json">&lt;link rel=<span class="hljs-string">"manifest"</span> href=<span class="hljs-string">"manifest.json"</span>&gt;
</code></pre>
<hr />
<h2 id="heading-step-3-create-a-service-worker">Step 3: Create a Service Worker</h2>
<p>A service worker is a JavaScript file that acts as a proxy between your website and the network. It handles caching and allows your app to work offline. Create a file named <code>service-worker.js</code> in your project root and add the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> CACHE_NAME = <span class="hljs-string">'pwa-cache-v1'</span>;
<span class="hljs-keyword">const</span> urlsToCache = [
  <span class="hljs-string">'/'</span>,
  <span class="hljs-string">'/index.html'</span>,
  <span class="hljs-string">'/styles.css'</span>,
  <span class="hljs-string">'/script.js'</span>,
  <span class="hljs-string">'/icons/icon-192x192.png'</span>,
  <span class="hljs-string">'/icons/icon-512x512.png'</span>
];

self.addEventListener(<span class="hljs-string">'install'</span>, <span class="hljs-function"><span class="hljs-params">event</span> =&gt;</span> {
  event.waitUntil(
    caches.open(CACHE_NAME).then(<span class="hljs-function"><span class="hljs-params">cache</span> =&gt;</span> {
      <span class="hljs-keyword">return</span> cache.addAll(urlsToCache);
    })
  );
});

self.addEventListener(<span class="hljs-string">'fetch'</span>, <span class="hljs-function"><span class="hljs-params">event</span> =&gt;</span> {
  event.respondWith(
    caches.match(event.request).then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> {
      <span class="hljs-keyword">return</span> response || fetch(event.request);
    })
  );
});

self.addEventListener(<span class="hljs-string">'activate'</span>, <span class="hljs-function"><span class="hljs-params">event</span> =&gt;</span> {
  event.waitUntil(
    caches.keys().then(<span class="hljs-function"><span class="hljs-params">cacheNames</span> =&gt;</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.all(
        cacheNames.map(<span class="hljs-function"><span class="hljs-params">cacheName</span> =&gt;</span> {
          <span class="hljs-keyword">if</span> (cacheName !== CACHE_NAME) {
            <span class="hljs-keyword">return</span> caches.delete(cacheName);
          }
        })
      );
    })
  );
});
</code></pre>
<p>Register the service worker in your main JavaScript file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-string">'serviceWorker'</span> <span class="hljs-keyword">in</span> navigator) {
  navigator.serviceWorker.register(<span class="hljs-string">'/service-worker.js'</span>)
    .then(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Service Worker registered successfully.'</span>))
    .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Service Worker registration failed:'</span>, error));
}
</code></pre>
<hr />
<h2 id="heading-step-4-enable-mobile-support">Step 4: Enable Mobile Support</h2>
<p>To ensure your PWA works seamlessly on mobile devices:</p>
<ol>
<li><p><strong>Make Your Website Responsive</strong>: Use CSS media queries or frameworks like Bootstrap or Tailwind CSS to create a responsive design that works on different screen sizes.</p>
</li>
<li><p><strong>Provide Mobile-Friendly Icons</strong>: Add icons with appropriate sizes in your <code>manifest.json</code>. Common sizes include 48x48, 72x72, 96x96, 144x144, 192x192, and 512x512.</p>
</li>
<li><p><strong>Test on Mobile Devices</strong>: Use Chrome DevTools to simulate various mobile devices or test directly on physical devices.</p>
</li>
</ol>
<hr />
<h2 id="heading-step-5-make-your-website-https-secure">Step 5: Make Your Website HTTPS Secure</h2>
<p>PWAs require HTTPS to ensure secure data exchange. If you’re hosting your website on platforms like GitHub Pages, Netlify, or Vercel, HTTPS is enabled by default. Otherwise, obtain an SSL certificate for your hosting provider.</p>
<hr />
<h2 id="heading-step-6-test-your-pwa">Step 6: Test Your PWA</h2>
<ol>
<li><p>Open your website in Google Chrome.</p>
</li>
<li><p>Use the <strong>Lighthouse</strong> tool in Chrome DevTools to audit your site for PWA compliance.</p>
</li>
<li><p>Check the "Application" tab in Chrome DevTools to ensure the service worker is active and the manifest is linked correctly.</p>
</li>
</ol>
<hr />
<h2 id="heading-step-7-deploy-your-pwa">Step 7: Deploy Your PWA</h2>
<p>Deploy your app to a hosting platform that supports HTTPS. Share the link with your users and encourage them to "Add to Home Screen" to install the PWA.</p>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>Creating a PWA from your HTML, CSS, and JavaScript website is a great way to enhance user experience and engagement. By following the steps above, you’ll have a fully functional PWA ready to impress your audience. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[A Beginner's Guide to Route Model Binding in Laravel]]></title><description><![CDATA[What is Route Model Binding?
Route model binding is a mechanism that binds a route parameter to a model. Instead of manually fetching a model instance from the database using the route parameter, Laravel does this for you automatically.
For example, ...]]></description><link>https://blog.aniknandi.pro/a-beginners-guide-to-route-model-binding-in-laravel</link><guid isPermaLink="true">https://blog.aniknandi.pro/a-beginners-guide-to-route-model-binding-in-laravel</guid><category><![CDATA[Route Model Binding]]></category><category><![CDATA[Laravel]]></category><category><![CDATA[PHP]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Programming Tips]]></category><dc:creator><![CDATA[Anik Kumar Nandi]]></dc:creator><pubDate>Wed, 25 Dec 2024 09:00:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1735114952998/cd765815-45e2-4c1b-8229-61139755b623.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-is-route-model-binding">What is Route Model Binding?</h2>
<p>Route model binding is a mechanism that binds a route parameter to a model. Instead of manually fetching a model instance from the database using the route parameter, <strong>Laravel</strong> does this for you automatically.</p>
<p>For example, in a typical route without model binding, you might write:</p>
<pre><code class="lang-php">Route::get(<span class="hljs-string">'/users/{id}'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$id</span>) </span>{
    $user = User::find($id);

    <span class="hljs-keyword">if</span>(!$user){
        <span class="hljs-keyword">return</span> abort(<span class="hljs-number">404</span>,<span class="hljs-string">"User not found"</span>);
    }

    <span class="hljs-keyword">return</span> view(<span class="hljs-string">'user.profile'</span>, [<span class="hljs-string">'user'</span> =&gt; $user]);
});
</code></pre>
<p>With route model binding, this can be simplified to:</p>
<pre><code class="lang-php">Route::get(<span class="hljs-string">'/users/{user}'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">User $user</span>) </span>{
    <span class="hljs-keyword">return</span> view(<span class="hljs-string">'user.profile'</span>, [<span class="hljs-string">'user'</span> =&gt; $user]);
});
</code></pre>
<p>As you can see, the code is simpler and cleaner. <strong>Laravel</strong> automatically finds the user based on the <code>id</code> parameter.</p>
<hr />
<h3 id="heading-1-route-model-binding">1. Route Model Binding</h3>
<p><strong>Laravel</strong> automatically finds the model for you based on the route parameter name. Here's an example:</p>
<p><strong>Route Definition:</strong></p>
<pre><code class="lang-php">Route::get(<span class="hljs-string">'/posts/{post}'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Post $post</span>) </span>{
    <span class="hljs-keyword">return</span> view(<span class="hljs-string">'posts.show'</span>, [<span class="hljs-string">'post'</span> =&gt; $post]);
});
</code></pre>
<p>In this case, Laravel uses the <code>id</code> column to find the post in the database. You don’t need to write any extra code!</p>
<p><strong>Controller Example:</strong></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">show</span>(<span class="hljs-params">Post $post</span>)
</span>{
    <span class="hljs-keyword">return</span> view(<span class="hljs-string">'posts.show'</span>, [<span class="hljs-string">'post'</span> =&gt; $post]);
}
</code></pre>
<p><strong>Note</strong>: You must use the same parameter name in both the route and the method. As you can see, we define the <code>/{post}</code> parameter in the route, and we also define the <code>post</code> parameter in the show method.</p>
<h4 id="heading-using-a-custom-column">Using a Custom Column</h4>
<p>Sometimes, you might want to use a column other than <code>id</code> to find the model. You can do this by adding a method to your model:</p>
<pre><code class="lang-php"><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">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getRouteKeyName</span>(<span class="hljs-params"></span>)
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'slug'</span>;
    }
}
</code></pre>
<p>Now, <strong>Laravel</strong> will look for a post using the <code>slug</code> column instead of <code>id</code>.</p>
<hr />
<h2 id="heading-what-happens-if-a-model-is-missing">What Happens if a Model is Missing?</h2>
<p>If Laravel can’t find the model, it will show a 404 error by default. You can customize this behavior by editing the <code>render</code> method in the <code>Handler</code> class.</p>
<pre><code class="lang-php"><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">ModelNotFoundException</span>;

<span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">render</span>(<span class="hljs-params">$request, <span class="hljs-built_in">Throwable</span> $exception</span>)
</span>{
    <span class="hljs-keyword">if</span> ($exception <span class="hljs-keyword">instanceof</span> ModelNotFoundException) {
        <span class="hljs-keyword">return</span> response()-&gt;view(<span class="hljs-string">'errors.404'</span>, [], <span class="hljs-number">404</span>);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-built_in">parent</span>::render($request, $exception);
}
</code></pre>
<hr />
<h2 id="heading-why-use-route-model-binding">Why Use Route Model Binding?</h2>
<ol>
<li><p><strong>Saves Time:</strong> You don’t need to write extra code to fetch models.</p>
</li>
<li><p><strong>Cleaner Code:</strong> Your routes and controllers are easier to read.</p>
</li>
<li><p><strong>Customizable:</strong> You can use any column (like <code>slug</code>) for route model binding.</p>
</li>
<li><p><strong>Consistent Behavior:</strong> Centralized logic for fetching models.</p>
</li>
</ol>
<p><strong>Note</strong>: I wrote this article to be super beginner-friendly, so you can discover Route Model Binding in just a minute. If you're interested in more advanced features, be sure to check out the official Laravel documentation.</p>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>Route model binding is a beginner-friendly feature that makes working with Laravel routes much easier. It reduces the amount of code you need to write and keeps everything clean and organized. Start using it today to make your Laravel projects more efficient!</p>
]]></content:encoded></item><item><title><![CDATA[Laravel SQL Injection Prevention: A Comprehensive Guide]]></title><description><![CDATA[SQL Injection is a common and serious issue in web apps. It allows attackers to run any SQL queries on your database, which could lead to data breaches, data loss, or even taking over your app's backend. As a Laravel developer, it's really important ...]]></description><link>https://blog.aniknandi.pro/laravel-sql-injection-prevention-a-comprehensive-guide</link><guid isPermaLink="true">https://blog.aniknandi.pro/laravel-sql-injection-prevention-a-comprehensive-guide</guid><category><![CDATA[anik nandi]]></category><category><![CDATA[anik kumar nandi]]></category><category><![CDATA[Laravel]]></category><category><![CDATA[SQL]]></category><category><![CDATA[#sqlinjection]]></category><category><![CDATA[laravel security]]></category><dc:creator><![CDATA[Anik Kumar Nandi]]></dc:creator><pubDate>Sat, 30 Nov 2024 07:25:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1732950406044/7a7235bd-9056-4433-9091-394ff3ad190b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>SQL Injection is a common and serious issue in web apps. It allows attackers to run any SQL queries on your database, which could lead to data breaches, data loss, or even taking over your app's backend. As a Laravel developer, it's really important to understand SQL Injection and how Laravel helps you prevent it. In this blog, we'll explore what SQL Injection is, the risks it poses, and the best ways to keep your Laravel app secure.</p>
<h2 id="heading-what-is-sql-injection"><strong>What is SQL Injection?</strong></h2>
<p>SQL Injection happens when someone with bad intentions changes a SQL query by sneaking in harmful input into a web app's query string. This can occur if user inputs are added directly into SQL statements without being properly cleaned or escaped.</p>
<h3 id="heading-example-of-sql-injection"><strong>Example of SQL Injection</strong></h3>
<p>Consider the following raw SQL query:</p>
<pre><code class="lang-php">$username = $_GET[<span class="hljs-string">'username'</span>];
$password = $_GET[<span class="hljs-string">'password'</span>];

$sql = <span class="hljs-string">"SELECT * FROM users WHERE username = '<span class="hljs-subst">$username</span>' AND password = '<span class="hljs-subst">$password</span>'"</span>;
</code></pre>
<p>If an attacker inputs the following:</p>
<ul>
<li><p><code>$username = anik</code></p>
</li>
<li><p><code>$password = ' OR '1'='1</code></p>
</li>
</ul>
<p>The resulting query becomes:</p>
<pre><code class="lang-php">SELECT * <span class="hljs-keyword">FROM</span> users WHERE username = <span class="hljs-string">'anik'</span> <span class="hljs-keyword">AND</span> password = <span class="hljs-string">''</span> <span class="hljs-keyword">OR</span> <span class="hljs-string">'1'</span>=<span class="hljs-string">'1'</span>;
</code></pre>
<p>This query will always return true, allowing unauthorized access.</p>
<hr />
<h2 id="heading-how-laravel-protects-against-sql-injection"><strong>How Laravel Protects Against SQL Injection</strong></h2>
<p>Laravel comes with some great built-in features to keep SQL Injection at bay. By following Laravel's best practices, you can really cut down on the chances of these attacks happening.</p>
<h3 id="heading-1-query-builder"><strong>1. Query Builder</strong></h3>
<p>Laravel's Query Builder automatically escapes input values, preventing SQL Injection. Instead of using raw SQL, use the query builder to construct queries.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-php">$users = DB::table(<span class="hljs-string">'users'</span>)
            -&gt;where(<span class="hljs-string">'username'</span>, $username)
            -&gt;where(<span class="hljs-string">'password'</span>, $password)
            -&gt;get();
</code></pre>
<p>The query builder ensures that <code>$username</code> and <code>$password</code> are escaped, making it safe from injection.</p>
<hr />
<h3 id="heading-2-eloquent-orm"><strong>2. Eloquent ORM</strong></h3>
<p>Eloquent ORM simplifies database operations and abstracts away raw queries. It ensures input values are properly sanitized.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-php">$user = User::where(<span class="hljs-string">'username'</span>, $username)-&gt;where(<span class="hljs-string">'password'</span>, $password)-&gt;first();
</code></pre>
<p>Eloquent also protects against SQL Injection by binding input parameters securely.</p>
<hr />
<h3 id="heading-3-parameterized-statements"><strong>3. Parameterized Statements</strong></h3>
<p>Parameterized statements keep SQL logic and user input separate, ensuring that anything users enter is treated as data and not as executable SQL.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-php">$results = DB::select(<span class="hljs-string">'SELECT * FROM users WHERE username = ? AND password = ?'</span>, [$username, $password]);
</code></pre>
<p>Using <code>?</code> as placeholders ensures the inputs are sanitized and prevents malicious SQL execution.</p>
<hr />
<h3 id="heading-4-using-binding-in-raw-queries"><strong>4. Using Binding in Raw Queries</strong></h3>
<p>When raw queries are unavoidable, always use bindings to safely include user inputs.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-php">$results = DB::select(<span class="hljs-string">'SELECT * FROM users WHERE username = :username AND password = :password'</span>, [
    <span class="hljs-string">'username'</span> =&gt; $username,
    <span class="hljs-string">'password'</span> =&gt; $password,
]);
</code></pre>
<p>This approach ensures input values are escaped and safe for execution.</p>
<hr />
<h3 id="heading-5-validation-and-sanitization"><strong>5. Validation and Sanitization</strong></h3>
<p>Laravel's validation system can help ensure that user inputs are clean and meet expected formats before reaching the database.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-php">$request-&gt;validate([
    <span class="hljs-string">'username'</span> =&gt; <span class="hljs-string">'required|string|max:255'</span>,
    <span class="hljs-string">'password'</span> =&gt; <span class="hljs-string">'required|string|min:8'</span>,
]);
</code></pre>
<p>Sanitizing input data can also help mitigate risks.</p>
<hr />
<h3 id="heading-6-avoiding-dynamic-queries"><strong>6. Avoiding Dynamic Queries</strong></h3>
<p>Avoid constructing SQL queries dynamically with user inputs. If you must use dynamic SQL, ensure all inputs are sanitized.</p>
<p><strong>Bad Example:</strong></p>
<pre><code class="lang-php">$sql = <span class="hljs-string">"SELECT * FROM users WHERE username = '<span class="hljs-subst">$username</span>'"</span>;
</code></pre>
<p><strong>Good Example:</strong></p>
<pre><code class="lang-php">$sql = <span class="hljs-string">"SELECT * FROM users WHERE username = ?"</span>;
DB::select($sql, [$username]);
</code></pre>
<hr />
<h3 id="heading-7-enable-query-logging-in-development"><strong>7. Enable Query Logging in Development</strong></h3>
<p>Use Laravel's query logging to monitor raw queries during development and identify potential vulnerabilities.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-php">DB::enableQueryLog();
$queries = DB::getQueryLog();
</code></pre>
<h3 id="heading-8-regularly-update-laravel-and-dependencies"><strong>8. Regularly Update Laravel and Dependencies</strong></h3>
<p>Keep Laravel, PHP, and database software updated to patch vulnerabilities and take advantage of security improvements.</p>
<hr />
<h2 id="heading-testing-for-sql-injection"><strong>Testing for SQL Injection</strong></h2>
<p>To test your Laravel application for SQL Injection vulnerabilities:</p>
<ol>
<li><p>Use tools like <a target="_blank" href="https://sqlmap.org/">sqlmap</a> for automated testing.</p>
</li>
<li><p>Manually test inputs with special characters like <code>'</code>, <code>"</code>, <code>;</code>, <code>--</code>.</p>
</li>
<li><p>Include SQL Injection tests in your automated test suite.</p>
</li>
</ol>
<hr />
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>SQL Injection is a serious security risk, but don't worry—Laravel has some great tools to help you prevent it. By using Query Builder, Eloquent ORM, parameterized statements, and proper validation, you can protect your application from SQL Injection attacks. Always stick to best practices and keep security at the top of your mind during development.</p>
<p>Secure your Laravel application today and protect your data from potential threats! 🚀</p>
]]></content:encoded></item><item><title><![CDATA[Essential Tips for Securing Your Laravel 11 App from DDoS Attacks]]></title><description><![CDATA[What Is a DDoS Attack?
A DDoS attack happens when lots of computers flood a server with too much traffic, aiming to slow it down or even knock it offline. It's like if hundreds of people tried to rush into a store all at once, causing a big jam that ...]]></description><link>https://blog.aniknandi.pro/essential-tips-for-securing-your-laravel-11-app-from-ddos-attacks</link><guid isPermaLink="true">https://blog.aniknandi.pro/essential-tips-for-securing-your-laravel-11-app-from-ddos-attacks</guid><category><![CDATA[WAFs]]></category><category><![CDATA[Laravel]]></category><category><![CDATA[ddos attacks]]></category><category><![CDATA[Security]]></category><category><![CDATA[ddos]]></category><dc:creator><![CDATA[Anik Kumar Nandi]]></dc:creator><pubDate>Mon, 11 Nov 2024 15:38:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1731339604198/52ba7aac-6f6c-4035-911f-1d6120bd3df8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-what-is-a-ddos-attack">What Is a DDoS Attack?</h3>
<p>A DDoS attack happens when lots of computers flood a server with too much traffic, aiming to slow it down or even knock it offline. It's like if hundreds of people tried to rush into a store all at once, causing a big jam that stops anyone from getting in normally. In a Laravel app, DDoS attacks might focus on pages like login, registration, and API endpoints, overwhelming them and possibly crashing the app.</p>
<p>To protect against these attacks, you'll want to make it tougher for bad traffic to hit these points without messing up the experience for real users. Let's explore some simple techniques you can use in Laravel.</p>
<hr />
<h3 id="heading-1-login-form-protection-using-rate-limiting-and-captcha">1. <strong>Login Form Protection: Using Rate Limiting and CAPTCHA</strong></h3>
<p>The login form is one of the most at-risk areas because attackers might try to break into user accounts or flood the server with too many login attempts. Here's how you can keep it safe:</p>
<p><strong>Step 1: Apply Rate Limiting</strong></p>
<p>Laravel has a built-in feature to limit the number of requests that any user can make within a certain time frame. Adding rate limiting to the login route restricts the number of login attempts, helping prevent attacks.</p>
<pre><code class="lang-php"> Route::post(<span class="hljs-string">'/login'</span>, [AuthController::class, <span class="hljs-string">'login'</span>])-&gt;middleware(<span class="hljs-string">'throttle:5,1'</span>);
</code></pre>
<p>This line limits users to <strong>five login attempts per minute</strong>. If they exceed this limit, Laravel will return an error response, which slows down potential attackers.</p>
<p><strong>Step 2: Add CAPTCHA Verification</strong></p>
<p>CAPTCHA is a simple challenge (like clicking on images or typing a code) that humans can easily complete, but bots usually can't. By adding CAPTCHA to the login form, you make sure that only real users can get through.</p>
<ul>
<li><strong>Google reCAPTCHA</strong> is a popular choice and it's free to use. Just register your site on the Google reCAPTCHA website, add the CAPTCHA keys to your <code>.env</code> file, and include the CAPTCHA code in your login form.</li>
</ul>
<p><strong>Example:</strong> If an attacker tries to overwhelm your login form with bot traffic, rate limiting will slow down their requests, and the CAPTCHA will stop automated bots from completing the form.</p>
<hr />
<h3 id="heading-2-registration-form-protection-ip-blocking-and-honeypots">2. <strong>Registration Form Protection: IP Blocking and Honeypots</strong></h3>
<p>If you allow new users to register, this form can also become a target. Attackers may attempt to create fake accounts, which could drain resources or manipulate referral programs.</p>
<p><strong>Step 1: Block Suspicious IPs and Apply Rate Limits</strong></p>
<p>Just like in the login form, limit how often a single IP can submit the registration form.</p>
<pre><code class="lang-php">Route::post(<span class="hljs-string">'/register'</span>, [RegistrationController::class, <span class="hljs-string">'register'</span>])-&gt;middleware(<span class="hljs-string">'throttle:3,60'</span>);
</code></pre>
<p>This limits each IP to <strong>three registrations per hour</strong>.</p>
<p><strong>Step 2: Use a Honeypot Field</strong></p>
<p>A honeypot is a hidden field in your form. Real users won’t fill it out since it’s hidden, but bots tend to fill in all form fields automatically. If this hidden field is filled out, you know it’s likely a bot.</p>
<p>To add a honeypot in Laravel, use the <code>spatie/laravel-honeypot</code> package. Here’s how:</p>
<ol>
<li><p>Run <code>composer require spatie/laravel-honeypot</code> to install the package.</p>
</li>
<li><p>Add the <code>@honeypot</code> directive to your form:</p>
<pre><code class="lang-xml"> <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"POST"</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"/register"</span>&gt;</span>
     @csrf
     @honeypot
     <span class="hljs-comment">&lt;!-- other form fields here --&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
</li>
</ol>
<p><strong>Example:</strong> If a bot tries to create hundreds of fake accounts, rate limiting and the honeypot field together will make it harder for the bot to succeed without alerting you to its activity.</p>
<hr />
<h3 id="heading-3-api-endpoints-throttle-requests-and-require-tokens">3. <strong>API Endpoints: Throttle Requests and Require Tokens</strong></h3>
<p>APIs are often used to serve data to your front-end or mobile app, but they’re also a common target for DDoS attacks. Here’s how to protect them:</p>
<p><strong>Step 1: Apply Throttle Middleware</strong></p>
<p>Limit how many times an API endpoint can be accessed in a short period. For example:</p>
<pre><code class="lang-php">Route::middleware(<span class="hljs-string">'throttle:10,1'</span>)-&gt;group(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    Route::get(<span class="hljs-string">'/search'</span>, [SearchController::class, <span class="hljs-string">'search'</span>]);
});
</code></pre>
<p>This limits users to <strong>10 searches per minute</strong>.</p>
<p><strong>Step 2: Require Token-Based Access</strong></p>
<p>For sensitive or private API endpoints, make sure users provide an authentication token. You can use packages like Laravel Sanctum or Passport to set up token-based authentication. This way, users need to log in and get a token before they can use certain API features.</p>
<p><strong>Example:</strong> If someone tries to attack your search API, they'll be limited to a certain number of requests. Plus, without the right tokens, they won't be able to access the endpoint at all.</p>
<hr />
<h3 id="heading-4-checkout-and-payment-pages-web-application-firewalls-and-queueing">4. <strong>Checkout and Payment Pages: Web Application Firewalls and Queueing</strong></h3>
<p>Checkout pages are super important for your app. If attackers target these pages, it could really hurt your revenue. Here's how you can keep these critical areas safe:</p>
<p><strong>Step 1: Set Up a Web Application Firewall (WAF)</strong></p>
<p>A WAF acts like a security guard between your server and the internet. It checks incoming requests and blocks anything that looks fishy. Services like Cloudflare and AWS WAF are great for defending against DDoS attacks.</p>
<p><strong>Step 2: Queue Backend Processes</strong></p>
<p>In Laravel, you can use queues to handle tasks in the background. For instance, when a user makes a purchase, you might want to send them a confirmation email. Instead of sending it immediately, you can queue it to be processed later, which helps reduce server load during busy times.</p>
<p><strong>Example:</strong> If someone tries to overwhelm your checkout page with fake orders, the WAF can block those suspicious IPs. Meanwhile, queued processes help keep your server running smoothly for genuine customers.</p>
<hr />
<h3 id="heading-5-interactive-forms-eg-feedback-forms-adding-delays-and-limiting-data-size">5. <strong>Interactive Forms (e.g. Feedback Forms): Adding Delays and Limiting Data Size</strong></h3>
<p>Interactive forms are another target for bots, especially if they can submit text data (like feedback). Bots might try to spam this form with junk data, so here’s what you can do:</p>
<p><strong>Step 1: Introduce Progressive Delays</strong></p>
<p>Add a delay between submissions. If a single IP keeps submitting the form repeatedly, progressively increase the delay between allowed submissions.</p>
<pre><code class="lang-php">$attempts = Cache::get(<span class="hljs-string">"feedback_attempts_<span class="hljs-subst">{$request-&gt;ip()}</span>"</span>, <span class="hljs-number">0</span>);
<span class="hljs-keyword">if</span> ($attempts &gt; <span class="hljs-number">3</span>) {
    sleep($attempts); <span class="hljs-comment">// Progressive delay as attempts increase</span>
}
Cache::put(<span class="hljs-string">"feedback_attempts_<span class="hljs-subst">{$request-&gt;ip()}</span>"</span>, $attempts + <span class="hljs-number">1</span>, now()-&gt;addMinutes(<span class="hljs-number">10</span>));
</code></pre>
<p><strong>Step 2: Limit the Data Size for Each Field</strong></p>
<p>Limit the length of data a user can submit in each field to avoid large payload attacks. Here’s an example of how to set limits in your controller:</p>
<pre><code class="lang-php">$request-&gt;validate([
    <span class="hljs-string">'feedback'</span> =&gt; <span class="hljs-string">'required|string|max:500'</span>,
    <span class="hljs-string">'username'</span> =&gt; <span class="hljs-string">'required|string|max:100'</span>,
]);
</code></pre>
<p><strong>Example:</strong> If bots try to flood your feedback form, adding delays and limiting the data size can slow them down and stop them from sending too much data.</p>
<hr />
<h3 id="heading-6-monitor-activity-with-real-time-alerts">6. <strong>Monitor Activity with Real-Time Alerts</strong></h3>
<p>Keeping an eye on your application's activity is a great way to catch attacks early. You can use Laravel's logging features or tools like Sentry or Papertrail to set up real-time alerts for any unusual traffic or patterns.</p>
<p><strong>Example:</strong> If there's a sudden increase in traffic to your API endpoint, you'll get an alert. This means you can quickly respond by increasing rate limits or blocking specific IPs.</p>
<hr />
<h3 id="heading-conclusion">Conclusion</h3>
<p>DDoS attacks can be tough to deal with, but you can make it harder for attackers to mess with your Laravel app by using simple protections like rate limiting, CAPTCHAs, and honeypots, along with improving backend processes with queues and WAFs. Start with these easy steps and add more security as needed.</p>
<p>These steps will help keep your app running smoothly and accessible to real users, even when it's under attack. Remember, the best defense is having multiple layers of protection across all entry points, from login and registration forms to API and checkout endpoints.</p>
]]></content:encoded></item><item><title><![CDATA[How to Set Up GitHub in a Local Environment on Ubuntu]]></title><description><![CDATA[Step 1: Install Git
Git is an essential tool for version control, allowing you to track changes to your code, collaborate with others, and maintain a history of your projects. On Ubuntu, installing Git is straightforward:

Update Your System:

Before...]]></description><link>https://blog.aniknandi.pro/how-to-set-up-github-in-a-local-environment-on-ubuntu</link><guid isPermaLink="true">https://blog.aniknandi.pro/how-to-set-up-github-in-a-local-environment-on-ubuntu</guid><category><![CDATA[github on ubuntu]]></category><category><![CDATA[github in ubuntu]]></category><category><![CDATA[Set Up GitHub on Ubuntu]]></category><category><![CDATA[github local environment]]></category><category><![CDATA[GitHub setup]]></category><category><![CDATA[Ubuntu]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[Git]]></category><category><![CDATA[Linux]]></category><category><![CDATA[git and github in linux]]></category><category><![CDATA[ssh-keys]]></category><category><![CDATA[ssh]]></category><dc:creator><![CDATA[Anik Kumar Nandi]]></dc:creator><pubDate>Sun, 10 Nov 2024 17:27:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1731258213202/d119272b-7352-4166-a434-c247ee3d2bb0.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-step-1-install-git">Step 1: Install Git</h3>
<p>Git is an essential tool for version control, allowing you to track changes to your code, collaborate with others, and maintain a history of your projects. On Ubuntu, installing Git is straightforward:</p>
<ol>
<li><p><strong>Update Your System</strong>:</p>
<ul>
<li>Before installing new software, it’s always a good idea to update your package list to get the latest version of the repository listings.</li>
</ul>
</li>
</ol>
<pre><code class="lang-yaml">    <span class="hljs-string">sudo</span> <span class="hljs-string">apt</span> <span class="hljs-string">update</span>
</code></pre>
<ol start="2">
<li><p><strong>Install Git</strong>:</p>
<ul>
<li>The following command will download and install Git.</li>
</ul>
</li>
</ol>
<pre><code class="lang-yaml">    <span class="hljs-string">sudo</span> <span class="hljs-string">apt</span> <span class="hljs-string">install</span> <span class="hljs-string">git</span> <span class="hljs-string">-y</span>
</code></pre>
<ol start="3">
<li><p><strong>Verify Installation</strong>:</p>
<ul>
<li>Confirm that Git was installed correctly by checking the version:</li>
</ul>
</li>
</ol>
<pre><code class="lang-yaml">    <span class="hljs-string">git</span> <span class="hljs-string">--version</span>
</code></pre>
<ul>
<li>This command should return the current Git version.</li>
</ul>
<hr />
<h3 id="heading-step-2-configure-git">Step 2: Configure Git</h3>
<p>After installing Git, set your user information. This information is tied to each commit, letting collaborators know who authored specific changes.</p>
<ol>
<li><p><strong>Set Your Git Username</strong>:</p>
<pre><code class="lang-yaml"> <span class="hljs-string">git</span> <span class="hljs-string">config</span> <span class="hljs-string">--global</span> <span class="hljs-string">user.name</span> <span class="hljs-string">"Your Name"</span>
</code></pre>
</li>
<li><p><strong>Set Your Git Email</strong>:</p>
<pre><code class="lang-yaml"> <span class="hljs-string">git</span> <span class="hljs-string">config</span> <span class="hljs-string">--global</span> <span class="hljs-string">user.email</span> <span class="hljs-string">"your.email@example.com"</span>
</code></pre>
<ul>
<li>GitHub uses this email to associate your commits with your GitHub account, so make sure it matches the email on your GitHub profile if you want to link them.</li>
</ul>
</li>
<li><p><strong>View Your Git Configuration</strong>:</p>
<pre><code class="lang-yaml"> <span class="hljs-string">git</span> <span class="hljs-string">config</span> <span class="hljs-string">--list</span>
</code></pre>
<ul>
<li>This will display your Git settings and confirm they’re saved.</li>
</ul>
</li>
</ol>
<hr />
<h3 id="heading-step-3-generate-ssh-keys">Step 3: Generate SSH Keys</h3>
<p>SSH (Secure Shell) keys allow you to securely connect to GitHub without needing to enter your password every time. GitHub uses SSH keys to authenticate your identity.</p>
<ol>
<li><p><strong>Generate a New SSH Key</strong>:</p>
<ul>
<li>Run the following command, replacing the email with the one you use for GitHub:</li>
</ul>
</li>
</ol>
<pre><code class="lang-yaml">    <span class="hljs-string">ssh-keygen</span> <span class="hljs-string">-t</span> <span class="hljs-string">ed25519</span> <span class="hljs-string">-C</span> <span class="hljs-string">"your.email@example.com"</span>
</code></pre>
<ul>
<li>When prompted, press <code>Enter</code> to save the key in the default location and add a <code>passphrase</code> for extra security if desired.</li>
</ul>
<blockquote>
<p><strong>What is SSH?</strong> SSH is a protocol that provides a secure way of accessing remote systems over a network. Using an SSH key pair (a private and a public key), you can securely connect your local machine with GitHub.</p>
</blockquote>
<hr />
<h3 id="heading-step-4-add-ssh-key-to-the-ssh-agent">Step 4: Add SSH Key to the SSH Agent</h3>
<p>The SSH agent manages your keys and helps you avoid re-entering your passphrase every time you use Git.</p>
<ol>
<li><p><strong>Start the SSH Agent</strong>:</p>
<pre><code class="lang-yaml"> <span class="hljs-string">eval</span> <span class="hljs-string">"$(ssh-agent -s)"</span>
</code></pre>
</li>
<li><p><strong>Add Your Key to the Agent</strong>:</p>
<pre><code class="lang-yaml"> <span class="hljs-string">ssh-add</span> <span class="hljs-string">~/.ssh/id_ed25519</span>
</code></pre>
</li>
</ol>
<p>This command ensures your SSH key is loaded and ready for GitHub to use.</p>
<hr />
<h3 id="heading-step-5-add-your-ssh-key-to-github">Step 5: Add Your SSH Key to GitHub</h3>
<p>Now, you need to register your SSH key with GitHub to grant your machine access.</p>
<ol>
<li><p><strong>Copy Your Public SSH Key</strong>:</p>
<pre><code class="lang-yaml"> <span class="hljs-string">cat</span> <span class="hljs-string">~/.ssh/id_ed25519.pub</span>
</code></pre>
<ul>
<li>Copy the output (your public key) to your clipboard.</li>
</ul>
</li>
<li><p><strong>Add the Key on GitHub</strong>:</p>
<ul>
<li><p>Go to GitHub and sign in.</p>
</li>
<li><p>In the upper-right corner, click on your profile picture, and select <strong>Settings</strong>.</p>
</li>
<li><p>Go to <strong>SSH and GPG keys</strong> on the left sidebar and click <strong>New SSH key</strong>.</p>
</li>
<li><p>Paste your SSH key into the "Key" field, give it a recognizable name (e.g., “Ubuntu-24-laptop”), and click <strong>Add SSH key</strong>.</p>
</li>
</ul>
</li>
</ol>
<hr />
<h3 id="heading-step-6-test-your-ssh-connection">Step 6: Test Your SSH Connection</h3>
<p>Once your key is added, test the SSH connection between your machine and GitHub.</p>
<ol>
<li><p>Run the following command to test:</p>
<pre><code class="lang-yaml"> <span class="hljs-string">ssh</span> <span class="hljs-string">-T</span> <span class="hljs-string">git@github.com</span>
</code></pre>
<p> If successful, you should see a message like:</p>
<blockquote>
<p>Hi yourusername! You've successfully authenticated, but GitHub does not provide shell access.</p>
</blockquote>
</li>
</ol>
<p>This message confirms your SSH key is working with GitHub.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Setting up GitHub on your local Ubuntu environment allows for easy code management, secure connections, and efficient collaboration. By installing Git, setting up SSH keys, and connecting your machine to GitHub, you can clone repositories, contribute to projects, and manage version control directly from your terminal. This setup lets you focus on coding while Git and GitHub take care of your project history and collaboration needs. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Laravel Queues: A Beginner's Guide]]></title><description><![CDATA[What is a Queue?
In a typical web application, some tasks, like sending an email or processing large amounts of data, can take time. If these tasks run directly within the request lifecycle, they can slow down the application and result in a poor use...]]></description><link>https://blog.aniknandi.pro/understanding-laravel-queues-a-beginners-guide</link><guid isPermaLink="true">https://blog.aniknandi.pro/understanding-laravel-queues-a-beginners-guide</guid><category><![CDATA[laravel queue]]></category><category><![CDATA[laravel scheduler]]></category><category><![CDATA[Laravel]]></category><category><![CDATA[queue]]></category><category><![CDATA[laravel task scheduling]]></category><dc:creator><![CDATA[Anik Kumar Nandi]]></dc:creator><pubDate>Tue, 05 Nov 2024 15:14:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730815747435/8e5ecfee-0331-46dc-988d-03b5dfe371e4.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-is-a-queue">What is a Queue?</h2>
<p>In a typical web application, some tasks, like sending an email or processing large amounts of data, can take time. If these tasks run directly within the request lifecycle, they can slow down the application and result in a poor user experience. Laravel Queues allow you to push these time-consuming tasks to the background, enabling them to run asynchronously and allowing the user to get a quicker response.</p>
<p>Laravel’s queue system supports several backends, including:</p>
<ul>
<li><p><strong>Database</strong></p>
</li>
<li><p><strong>Redis</strong></p>
</li>
<li><p><strong>Amazon SQS</strong></p>
</li>
<li><p><strong>Beanstalkd</strong></p>
</li>
</ul>
<p>Each of these backends stores jobs in a queue and manages the execution of these tasks.</p>
<h2 id="heading-setting-up-laravel-queues">Setting Up Laravel Queues</h2>
<h3 id="heading-step-1-configure-queue-driver">Step 1: Configure Queue Driver</h3>
<p>In your <code>.env</code> file, set the <code>QUEUE_CONNECTION</code></p>
<pre><code class="lang-plaintext">QUEUE_CONNECTION=database
</code></pre>
<p>Next, update the <code>config/queue.php</code> configuration file if needed, though the default settings for <code>database</code> are usually sufficient.</p>
<h3 id="heading-step-2-creating-queue-tables">Step 2: Creating Queue Tables</h3>
<p>If you're using the database driver, run:</p>
<pre><code class="lang-bash">php artisan queue:table
php artisan migrate
</code></pre>
<p><strong>Note</strong>: Laravel 11 creates the queue table by default, so check your <code>database/migrations</code> directory. If you see the <code>......create_jobs_table.php</code> file, you can skip the <code>php artisan queue:table</code> command. To check the migration status, run the <code>php artisan migrate:status</code> command. If this table hasn't been migrated, just run the <code>php artisan migrate</code> command.</p>
<h2 id="heading-creating-jobs">Creating Jobs</h2>
<p>To create a new job, use the <code>make:job</code> Artisan command. For instance, let’s create a job that sends a welcome email to a new user.</p>
<pre><code class="lang-bash">php artisan make:job SendWelcomeEmail
</code></pre>
<p>This command creates a job class in the <code>app/Jobs</code> directory. Open <code>SendWelcomeEmail.php</code> to see the default structure. Here, you can define the logic for the job in the <code>handle</code> method.</p>
<h3 id="heading-example-job-class">Example Job Class</h3>
<p>Let's say we want to send a welcome email to a user when they register. We can define the <code>SendWelcomeEmail</code> job like this:</p>
<pre><code class="lang-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Jobs</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">User</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Mail</span>\<span class="hljs-title">WelcomeEmail</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Bus</span>\<span class="hljs-title">Queueable</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Contracts</span>\<span class="hljs-title">Queue</span>\<span class="hljs-title">ShouldQueue</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Foundation</span>\<span class="hljs-title">Bus</span>\<span class="hljs-title">Dispatchable</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Queue</span>\<span class="hljs-title">InteractsWithQueue</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Queue</span>\<span class="hljs-title">SerializesModels</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">Mail</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SendWelcomeEmail</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">ShouldQueue</span>
</span>{
    <span class="hljs-keyword">use</span> <span class="hljs-title">Dispatchable</span>, <span class="hljs-title">InteractsWithQueue</span>, <span class="hljs-title">Queueable</span>, <span class="hljs-title">SerializesModels</span>;

    <span class="hljs-keyword">protected</span> $user;

    <span class="hljs-comment">/**
     * Create a new job instance.
     *
     * <span class="hljs-doctag">@return</span> void
     */</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">User $user</span>)
    </span>{
        <span class="hljs-keyword">$this</span>-&gt;user = $user;
    }

    <span class="hljs-comment">/**
     * Execute the job.
     *
     * <span class="hljs-doctag">@return</span> void
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handle</span>(<span class="hljs-params"></span>)
    </span>{
        Mail::to(<span class="hljs-keyword">$this</span>-&gt;user-&gt;email)-&gt;send(<span class="hljs-keyword">new</span> WelcomeEmail(<span class="hljs-keyword">$this</span>-&gt;user));
    }
}
</code></pre>
<p>In this example, the <code>SendWelcomeEmail</code> job takes a <code>User</code> object as a parameter and uses it to send an email. The <code>ShouldQueue</code> interface tells Laravel to queue this job instead of running it immediately.</p>
<h3 id="heading-dispatching-the-job">Dispatching the Job</h3>
<p>To push this job onto the queue, you simply call the <code>dispatch</code> method:</p>
<pre><code class="lang-php"><span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Jobs</span>\<span class="hljs-title">SendWelcomeEmail</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">User</span>;

$user = User::find(<span class="hljs-number">1</span>);
SendWelcomeEmail::dispatch($user);
</code></pre>
<p>This will add the <code>SendWelcomeEmail</code> job to the <code>jobs</code> table in your database, waiting for a worker to pick it up and process it.</p>
<hr />
<h2 id="heading-running-the-queue-worker">Running the Queue Worker</h2>
<p>To start processing jobs on the queue, run the following command:</p>
<pre><code class="lang-php">php artisan queue:work
</code></pre>
<p>This command will start a queue worker.</p>
<p>or you can also run:</p>
<pre><code class="lang-php">php artisan queue:listen
</code></pre>
<p>When using the <code>queue:listen</code> command, you don't have to manually restart the worker when you want to reload your updated code or reset the application state; however, this command is significantly less efficient than the <code>queue:work</code> command:</p>
<p>To run the queue in a production environment, it is necessary to set up Supervisor or a similar worker on your server. Learn more about Supervisor:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://notes.sohag.pro/supervisor-setup-for-laravel-application">https://notes.sohag.pro/supervisor-setup-for-laravel-application</a></div>
<p> </p>
<h2 id="heading-basic-example-queueing-a-job-on-user-registration">Basic Example: Queueing a Job on User Registration</h2>
<p>Let’s put everything together with a simple example. Suppose you want to send a welcome email whenever a new user registers. You could add this logic in your <code>UserController</code> or a listener for the <code>Registered</code> event.</p>
<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">User</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Jobs</span>\<span class="hljs-title">SendWelcomeEmail</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Request</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserController</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">register</span>(<span class="hljs-params">Request $request</span>)
    </span>{
        <span class="hljs-comment">// Validate and create the user</span>
        $user = User::create($request-&gt;all());

        <span class="hljs-comment">// Dispatch the welcome email job</span>
        SendWelcomeEmail::dispatch($user);

        <span class="hljs-keyword">return</span> response()-&gt;json([<span class="hljs-string">'message'</span> =&gt; <span class="hljs-string">'User registered and email sent!'</span>]);
    }
}
</code></pre>
<p>This example demonstrates how Laravel queues allow you to defer sending a welcome email by pushing the job to a queue. As a result, the user receives a faster response after registration.</p>
<hr />
<h2 id="heading-handling-failed-jobs">Handling Failed Jobs</h2>
<p>Sometimes, jobs may fail due to network issues or other errors. Laravel provides an easy way to handle these failures. When a job fails, Laravel writes the failed job’s information to a <code>failed_jobs</code> table.</p>
<pre><code class="lang-bash">php artisan queue:failed
</code></pre>
<p>If you want to retry all failed jobs, use:</p>
<pre><code class="lang-bash">php artisan queue:retry all
</code></pre>
<p>if you want to retry specific job</p>
<pre><code class="lang-bash">php artisan queue:retry {failed_job_ID}
</code></pre>
<p>If necessary, you may pass multiple IDs to the command:</p>
<pre><code class="lang-bash">php artisan queue:retry {failed_job_ID} {failed_job_ID}
</code></pre>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>Laravel Queues offer a powerful way to improve the responsiveness and scalability of your application by offloading time-consuming tasks. With a straightforward setup and robust error-handling features, Laravel queues allow you to easily process tasks asynchronously, enhancing the overall user experience.</p>
]]></content:encoded></item><item><title><![CDATA[How to Set Bash Aliases for Git Commands on Windows]]></title><description><![CDATA[In this blog post, I’ll walk you through setting up Git command aliases in a Windows environment by creating a .bashrc file. This file allows you to add shortcuts and customizations, making your workflow more efficient. We’ll also cover some Git-spec...]]></description><link>https://blog.aniknandi.pro/how-to-set-bash-aliases-for-git-commands-on-windows</link><guid isPermaLink="true">https://blog.aniknandi.pro/how-to-set-bash-aliases-for-git-commands-on-windows</guid><category><![CDATA[github alias]]></category><category><![CDATA[git alias]]></category><category><![CDATA[alias]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[git shortcut]]></category><category><![CDATA[github-commands]]></category><dc:creator><![CDATA[Anik Kumar Nandi]]></dc:creator><pubDate>Sun, 20 Oct 2024 05:15:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1729843754593/a78df149-4771-4ebb-9ccd-da480f12546b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this blog post, I’ll walk you through setting up Git command aliases in a Windows environment by creating a <code>.bashrc</code> file. This file allows you to add shortcuts and customizations, making your workflow more efficient. We’ll also cover some Git-specific aliases to speed up your daily tasks.</p>
<p><strong>Step 1: Create a</strong> <code>.bashrc</code> <strong>File in Windows.</strong></p>
<p>First, you’ll need to create a hidden <code>.bashrc</code> file in your user directory.</p>
<ol>
<li>Navigate to the directory where you want to create the file, typically:</li>
</ol>
<pre><code class="lang-plaintext">C:\Users\[your-username]/
</code></pre>
<p>To create the file:</p>
<ol start="2">
<li><ul>
<li><p>Open <strong>Notepad</strong> (or any text editor).</p>
<ul>
<li><p>Go to <strong>File</strong> &gt; <strong>Save As</strong>.</p>
</li>
<li><p>In the "File name" field, type <code>.bashrc.</code> (with the trailing dot). This is a trick to force Windows to save a file with no extension.</p>
</li>
<li><p>Save the file.</p>
</li>
</ul>
</li>
</ul>
</li>
<li><p>The file should now be visible in your user folder as <code>.bashrc</code>.</p>
</li>
</ol>
<h4 id="heading-step-2-add-aliases-to-cusersyour-usernamebashrc">Step 2: Add Aliases to <code>C:\Users\[your-username]\.bashrc</code></h4>
<p>Once the <code>.bashrc</code> file is created, it’s time to add some Git command aliases. These aliases act as shortcuts to common commands, helping you speed up repetitive tasks.</p>
<p>Here's how to add basic Git aliases to your <code>.bashrc</code> file, which you can modify as needed.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Add your own aliases or change these as you like</span>

<span class="hljs-comment"># Git Aliases</span>
<span class="hljs-built_in">alias</span> gst=<span class="hljs-string">'git status'</span>          <span class="hljs-comment"># Shortcut for 'git status'</span>
<span class="hljs-built_in">alias</span> gco=<span class="hljs-string">'git checkout'</span>        <span class="hljs-comment"># Shortcut for 'git checkout'</span>
<span class="hljs-built_in">alias</span> gbr=<span class="hljs-string">'git branch'</span>          <span class="hljs-comment"># Shortcut for 'git branch'</span>
<span class="hljs-built_in">alias</span> gad=<span class="hljs-string">'git add .'</span>           <span class="hljs-comment"># Add all changes</span>
<span class="hljs-built_in">alias</span> gcm=<span class="hljs-string">'git commit -m'</span>       <span class="hljs-comment"># Commit with a message</span>
<span class="hljs-built_in">alias</span> gps=<span class="hljs-string">'git push'</span>            <span class="hljs-comment"># Push changes</span>
<span class="hljs-built_in">alias</span> gpl=<span class="hljs-string">'git pull'</span>            <span class="hljs-comment"># Pull the latest changes</span>
<span class="hljs-built_in">alias</span> gdf=<span class="hljs-string">'git diff'</span>            <span class="hljs-comment"># View differences</span>
<span class="hljs-built_in">alias</span> glg=<span class="hljs-string">'git log --oneline'</span>   <span class="hljs-comment"># View a short log of commits</span>

<span class="hljs-comment"># General aliases</span>
<span class="hljs-built_in">alias</span> ls=<span class="hljs-string">'ls -alh'</span>              <span class="hljs-comment"># Show detailed file listing</span>
<span class="hljs-built_in">alias</span> ll=<span class="hljs-string">'ls -lah'</span>              <span class="hljs-comment"># List all files including hidden ones</span>
<span class="hljs-built_in">alias</span> clr=<span class="hljs-string">'clear'</span>               <span class="hljs-comment"># Clear terminal screen</span>
</code></pre>
<p>Each of these aliases represents a shortcut to a more complex command. For example, typing <code>gst</code> will run <code>git status</code>, and <code>gco</code> will run <code>git checkout</code>.</p>
<h4 id="heading-step-3-save-and-activate-the-aliases">Step 3: Save and Activate the Aliases</h4>
<p>After adding the aliases to the <code>.bashrc</code> file, save the changes. To apply these changes, open <strong>Git Bash</strong> and run the following command:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">source</span> ~/.bashrc
</code></pre>
<p>This command reloads the <code>.bashrc</code> file and applies the changes immediately. To ensure all changes take effect, <strong>close any existing terminal</strong> windows and reopen them before using the aliases.</p>
<h4 id="heading-step-4-verify-the-aliases">Step 4: Verify the Aliases</h4>
<p>To verify that your aliases are working, open your terminal and try running one of your new shortcuts. For example:</p>
<pre><code class="lang-bash">gst   <span class="hljs-comment"># Should show 'git status'</span>
gcm   <span class="hljs-comment"># Use like this: gcm "Your commit message"</span>
</code></pre>
<p><strong>Congratulations</strong>! You’ve successfully set up your Git aliases.</p>
<p><strong>Note</strong>: Setting up Git command aliases in Windows can save you a lot of time and effort. By following the steps in this guide, you can tailor your command-line experience to fit your workflow. Feel free to add, remove, or change aliases in your <code>.bashrc</code> file as needed to boost your productivity.</p>
]]></content:encoded></item><item><title><![CDATA[How Exercise Can Make Programmers More Productive]]></title><description><![CDATA[Fitness isn’t just about staying in shape—it’s a crucial element for peak performance and overall well-being. Regular exercise can boost your energy levels and improve your mood.
Regular exercise boosts blood flow to the brain, sharpening cognitive a...]]></description><link>https://blog.aniknandi.pro/how-exercise-can-make-programmers-more-productive</link><guid isPermaLink="true">https://blog.aniknandi.pro/how-exercise-can-make-programmers-more-productive</guid><category><![CDATA[Exercise]]></category><category><![CDATA[programmer]]></category><category><![CDATA[PHP]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[fitness]]></category><category><![CDATA[Databases]]></category><category><![CDATA[Productive]]></category><category><![CDATA[Java]]></category><category><![CDATA[Python]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Flutter]]></category><category><![CDATA[Dart]]></category><category><![CDATA[Android]]></category><category><![CDATA[gym]]></category><category><![CDATA[React]]></category><dc:creator><![CDATA[Anik Kumar Nandi]]></dc:creator><pubDate>Wed, 04 Sep 2024 18:23:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1725473648751/34879d4c-f528-42d9-b853-60b02fff267f.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Fitness isn’t just about staying in shape—it’s a crucial element for peak performance and overall well-being. Regular exercise can boost your energy levels and improve your mood.</p>
<p>Regular exercise boosts blood flow to the brain, sharpening cognitive abilities like memory and problem-solving. For programmers, this translates to clearer thinking and more effective tackling of complex coding challenges.</p>
<p>The pressure of tight deadlines and intricate coding can be stressful. Exercise triggers the release of endorphins, which act as natural stress relievers, helping to maintain a healthier work-life balance and reducing the risk of burnout.</p>
<p>Exercise stimulates brain function and encourages neurogenesis (the creation of new brain cells), fostering enhanced creativity. This can lead to innovative problem-solving and fresh perspectives on programming tasks.</p>
<p>Prolonged sitting can strain your body. Incorporating exercise, especially strength training and stretching, can improve posture and alleviate discomfort, helping you stay focused and less distracted.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725473851435/a735a132-d2f4-43e7-8561-57fddf34056a.jpeg" alt="Fitness" class="image--center mx-auto" /></p>
<p>Maintaining a fitness routine requires commitment and discipline—traits that are directly applicable to programming. Developing these habits can enhance your overall productivity and work ethic.</p>
<p>Engaging in fitness activities provides opportunities for social interaction outside of work. This can reduce feelings of isolation, offer new perspectives, and contribute positively to your professional life.</p>
<p>Incorporating fitness into your programming lifestyle not only supports physical health but also enhances mental clarity, creativity, and overall productivity. Make fitness a part of your routine to improve both your coding performance and your quality of life.</p>
]]></content:encoded></item></channel></rss>