<?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[Abhishek Jha]]></title><description><![CDATA[As a Full Stack Developer with four years of  extensive expertise in the field of PHP, Laravel, MySQL, Linux, HTML, JavaScript, Jquery &amp; Vue]]></description><link>https://blog.jhaabhishek.com</link><generator>RSS for Node</generator><lastBuildDate>Tue, 14 Apr 2026 22:34:14 GMT</lastBuildDate><atom:link href="https://blog.jhaabhishek.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[The Next Chapter for Software Product and Service Companies]]></title><description><![CDATA[The business model that built most software companies is under serious pressure.
The client has a problem. You build a system. They pay. Repeat.
That worked for two decades. It is not going to work fo]]></description><link>https://blog.jhaabhishek.com/the-next-chapter-for-software-product-and-service-companies</link><guid isPermaLink="true">https://blog.jhaabhishek.com/the-next-chapter-for-software-product-and-service-companies</guid><category><![CDATA[software-business]]></category><category><![CDATA[SaaS]]></category><category><![CDATA[product strategy]]></category><category><![CDATA[AI]]></category><dc:creator><![CDATA[Abhishek Jha]]></dc:creator><pubDate>Sun, 15 Mar 2026 07:48:19 GMT</pubDate><content:encoded><![CDATA[<p>The business model that built most software companies is under serious pressure.</p>
<p>The client has a problem. You build a system. They pay. Repeat.</p>
<p>That worked for two decades. It is not going to work for the next two.</p>
<hr />
<h2>What Is Actually Happening</h2>
<p>Clients are building software themselves.</p>
<p>Not complex systems. But with internal tools, basic workflows, simple dashboards, standard reports, a non-technical business owner can now get something working with AI tools without hiring anyone.</p>
<p>And here is what makes this more serious than it sounds: clients already have the hardest part of building good software, deep knowledge of their own business. AI tools just gave them the ability to act on it directly.</p>
<p>The demand for "build us what we described" is shrinking. That is not a prediction. It is already happening.</p>
<hr />
<h2>Who Gets Hit First</h2>
<p><strong>Custom agencies</strong> whose value is the execution of client briefs. When a client can describe the same brief to an AI and get something functional, the willingness to pay an agency drops fast.</p>
<p><strong>SaaS products</strong> are built around basic data management. If your core value is a clean interface for storing and retrieving data, you are competing with something clients can now configure themselves for near-zero cost.</p>
<p><strong>Implementation partners</strong> handling routine setup and integration work. AI is automating exactly that category of work.</p>
<p>The common thread: if your value is in doing well-defined tasks, that value is being automated.</p>
<hr />
<h2>What Is Not Going Away</h2>
<p>Software that reasons about data, not just stores it.</p>
<p>There is a real and growing gap between:</p>
<ul>
<li><p><strong>Managing data</strong>, storing what happened, showing it back, and alerting on thresholds. Clients can build this.</p>
</li>
<li><p><strong>Understanding data</strong> finding patterns nobody looked for, surfacing insights before anyone asked, and getting smarter over time. Clients cannot build this.</p>
</li>
</ul>
<p>That second category is where software companies have a defensible and growing market. It requires domain depth, architectural thinking, and a fundamentally different approach to what a product is supposed to do.</p>
<hr />
<h2>What Clients Are Actually Willing to Pay For Now</h2>
<p>Clients who can build basic software themselves are no longer impressed by it.</p>
<p>What they will pay for is software that makes their operation genuinely better. That surfaces what they would have missed. That reduces the decisions they should not have to make manually. That gets more valuable the longer it runs, not just on day one.</p>
<p>The question has shifted from <em>"does it have the features we need"</em> to <em>"does it actually improve how we operate."</em></p>
<p>Those are very different products.</p>
<hr />
<h2>The Companies That Come Out Ahead</h2>
<p>The ones that move from selling <strong>delivery</strong> to selling <strong>intelligence</strong>.</p>
<p>Specifically:</p>
<ul>
<li><p>Systems that learn from the client's own historical data and get more accurate over time</p>
</li>
<li><p>Insights the client did not know to ask for, patterns in years of data that were always there but invisible</p>
</li>
<li><p>Domain knowledge encoded into the product itself, not as templates and config options, but as a genuine understanding of how that industry works</p>
</li>
</ul>
<p>These are positions that get stronger as the market shifts. A system that has spent three years learning a client's specific operation is not easy to replace. That is real compounding value.</p>
<hr />
<h2>The Honest Summary</h2>
<p>Two types of software companies are heading into the next five years.</p>
<p>The ones still competing on delivery speed, feature completeness, and cost — on a playing field that is shrinking.</p>
<p>And the ones that have moved up into building intelligence, domain depth, and compounding value, on a playing field that is just opening up.</p>
<p>The shift does not have to happen overnight. But the direction has to be decided.</p>
]]></content:encoded></item><item><title><![CDATA[The Laravel Collection Vibe in Python]]></title><description><![CDATA[In the first lesson, we aligned Laravel arrays with Python lists to get comfortable. Now we level up. If Laravel gave you Collections and changed the way you think about data, Python gives you something just as expressive and, honestly, it’s surprisi...]]></description><link>https://blog.jhaabhishek.com/the-laravel-collection-vibe-in-python</link><guid isPermaLink="true">https://blog.jhaabhishek.com/the-laravel-collection-vibe-in-python</guid><category><![CDATA[Laravel]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[LaraveltoMachineLEarning]]></category><dc:creator><![CDATA[Abhishek Jha]]></dc:creator><pubDate>Sat, 14 Feb 2026 10:03:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1771063880921/f66ee5b3-d332-4092-a883-333238171405.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the first lesson, we aligned Laravel arrays with Python lists to get comfortable. Now we level up. If Laravel gave you Collections and changed the way you think about data, Python gives you something just as expressive and, honestly, it’s surprisingly elegant: <strong>list comprehensions</strong>. This is the moment when Python stops feeling like “another language to learn” and starts to feel familiar. You begin to realize you’re not starting from scratch; you’re just translating your developer instincts into a new syntax.</p>
<hr />
<h2 id="heading-from-collect-to-comprehension">From <code>collect()</code> to Comprehension</h2>
<p>In Laravel, when you want clean data transformation, you don’t write messy loops.</p>
<p>You write:</p>
<pre><code class="lang-php">collect($users)
    -&gt;filter(...)
    -&gt;map(...)
    -&gt;pluck(...);
</code></pre>
<p>In Python, instead of chaining methods, you compress that thinking into a readable one-liner.</p>
<p>Let’s see how that translates.</p>
<hr />
<h1 id="heading-transforming-data-like-gtmap">Transforming Data — Like <code>-&gt;map()</code></h1>
<pre><code class="lang-php">$doubled = collect($numbers)
    -&gt;map(<span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$n</span>) =&gt; $<span class="hljs-title">n</span> * 2)
    -&gt;<span class="hljs-title">all</span>(<span class="hljs-params"></span>)</span>;
</code></pre>
<pre><code class="lang-python">numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]

doubled = [n * <span class="hljs-number">2</span> <span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> numbers]
</code></pre>
<h3 id="heading-how-to-read-it">How to read it</h3>
<blockquote>
<p>“Give me n * 2 for each n in numbers.”</p>
</blockquote>
<p>Pattern:</p>
<pre><code class="lang-python">[expression <span class="hljs-keyword">for</span> variable <span class="hljs-keyword">in</span> iterable]
</code></pre>
<p>This is the most common pattern in Python.</p>
<p>And once you understand this structure, everything else builds on it.</p>
<hr />
<h1 id="heading-filtering-like-gtfilter">Filtering — Like <code>-&gt;filter()</code></h1>
<pre><code class="lang-php">collect($numbers)
    -&gt;filter(<span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$n</span>) =&gt; $<span class="hljs-title">n</span> % 2 == 0)
    -&gt;<span class="hljs-title">values</span>(<span class="hljs-params"></span>)
    -&gt;<span class="hljs-title">all</span>(<span class="hljs-params"></span>)</span>;
</code></pre>
<pre><code class="lang-python">evens = [n <span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> numbers <span class="hljs-keyword">if</span> n % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>]
</code></pre>
<p>Pattern:</p>
<pre><code class="lang-python">[expression <span class="hljs-keyword">for</span> variable <span class="hljs-keyword">in</span> iterable <span class="hljs-keyword">if</span> condition]
</code></pre>
<p>This is basically <code>filter()</code> + <code>map()</code> combined.</p>
<p>Python doesn't chain methods — it nests logic inside the comprehension.</p>
<hr />
<h1 id="heading-map-filter-in-one-line">Map + Filter in One Line</h1>
<pre><code class="lang-php">collect($names)
    -&gt;filter(<span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$n</span>) =&gt; <span class="hljs-title">strlen</span>(<span class="hljs-params">$n</span>) &gt; 3)
    -&gt;<span class="hljs-title">map</span>(<span class="hljs-params">fn(<span class="hljs-params">$n</span>) =&gt; strtoupper(<span class="hljs-params">$n</span>)</span>)</span>;
</code></pre>
<pre><code class="lang-python">names = [<span class="hljs-string">'Alice'</span>, <span class="hljs-string">'Bob'</span>, <span class="hljs-string">'Charlie'</span>, <span class="hljs-string">'David'</span>, <span class="hljs-string">'Eve'</span>]

long_upper = [name.upper() <span class="hljs-keyword">for</span> name <span class="hljs-keyword">in</span> names <span class="hljs-keyword">if</span> len(name) &gt; <span class="hljs-number">3</span>]
</code></pre>
<p>Same logic with less code, or you can say a one-liner.</p>
<hr />
<h1 id="heading-working-with-dicts-like-gtpluck">Working With Dicts — Like <code>-&gt;pluck()</code></h1>
<pre><code class="lang-php">collect($users)-&gt;pluck(<span class="hljs-string">'name'</span>)-&gt;all();
</code></pre>
<pre><code class="lang-python">users = [
    {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Alice'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">30</span>, <span class="hljs-string">'active'</span>: <span class="hljs-literal">True</span>},
    {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Bob'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">25</span>, <span class="hljs-string">'active'</span>: <span class="hljs-literal">False</span>},
    {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Charlie'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">35</span>, <span class="hljs-string">'active'</span>: <span class="hljs-literal">True</span>},
]

names_list = [user[<span class="hljs-string">'name'</span>] <span class="hljs-keyword">for</span> user <span class="hljs-keyword">in</span> users]
</code></pre>
<p>Filter + pluck:</p>
<pre><code class="lang-python">active_names = [
    user[<span class="hljs-string">'name'</span>] 
    <span class="hljs-keyword">for</span> user <span class="hljs-keyword">in</span> users 
    <span class="hljs-keyword">if</span> user[<span class="hljs-string">'active'</span>]
]
</code></pre>
<p>Once you see it, you can’t unsee it.</p>
<hr />
<h1 id="heading-building-dictionaries-like-gtkeyby">Building Dictionaries — Like <code>-&gt;keyBy()</code></h1>
<p>Laravel:</p>
<pre><code class="lang-php">collect($users)-&gt;keyBy(<span class="hljs-string">'name'</span>);
</code></pre>
<pre><code class="lang-python">users_by_name = {
    user[<span class="hljs-string">'name'</span>]: user 
    <span class="hljs-keyword">for</span> user <span class="hljs-keyword">in</span> users
}
</code></pre>
<p>Pattern:</p>
<pre><code class="lang-python">{key: value <span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> iterable}
</code></pre>
<p>This is called a <strong>dict comprehension</strong>.</p>
<p>You’re building lookup structures instantly.</p>
<hr />
<h1 id="heading-unique-values-like-gtunique">Unique Values — Like <code>-&gt;unique()</code></h1>
<pre><code class="lang-php">collect($ages)-&gt;unique();
</code></pre>
<pre><code class="lang-python">ages = [<span class="hljs-number">25</span>, <span class="hljs-number">30</span>, <span class="hljs-number">25</span>, <span class="hljs-number">35</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>]
unique_ages = {age <span class="hljs-keyword">for</span> age <span class="hljs-keyword">in</span> ages}
</code></pre>
<p>Curly braces without <code>:</code> mean <strong>set comprehension</strong>.</p>
<p>Sets automatically remove duplicates.</p>
<hr />
<h1 id="heading-flattening-like-gtflatten">Flattening — Like <code>-&gt;flatten()</code></h1>
<pre><code class="lang-php">collect($matrix)-&gt;flatten();
</code></pre>
<pre><code class="lang-python">matrix = [[<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>],[<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>],[<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>]]

flat = [num <span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> matrix <span class="hljs-keyword">for</span> num <span class="hljs-keyword">in</span> row]

<span class="hljs-comment">#Detailed example of shorthand</span>
flat = []

<span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> matrix:
    <span class="hljs-keyword">for</span> num <span class="hljs-keyword">in</span> row:
        flat.append(num)
</code></pre>
<p>Read it carefully:</p>
<blockquote>
<p>“For each row in matrix, for each num in row.”</p>
</blockquote>
<p>Nested logic, single expression.</p>
<hr />
<h1 id="heading-when-not-to-use-comprehensions">When NOT to Use Comprehensions</h1>
<p>As a Laravel dev, you already value readability.</p>
<p>Don’t use comprehensions when:</p>
<ul>
<li><p>Logic becomes too complex</p>
</li>
<li><p>You need side effects (saving, printing, logging)</p>
</li>
<li><p>The expression becomes hard to read</p>
</li>
</ul>
<p>Clean code &gt; clever code.</p>
<hr />
<h1 id="heading-why-this-matters-for-ml">Why This Matters for ML</h1>
<p>This isn’t just syntax sugar.</p>
<p>In Machine Learning, you will:</p>
<ul>
<li><p>Clean datasets</p>
</li>
<li><p>Transform features</p>
</li>
<li><p>Filter records</p>
</li>
<li><p>Build lookup maps</p>
</li>
<li><p>Generate derived values</p>
</li>
</ul>
<p>And you’ll do it constantly.</p>
<p>List comprehensions train your brain to:</p>
<ul>
<li><p>Think in transformations</p>
</li>
<li><p>Write declarative logic</p>
</li>
<li><p>Manipulate datasets efficiently</p>
</li>
</ul>
<p>This is the bridge between a <strong>backend developer</strong> and an <strong>ML engineer</strong>.</p>
<hr />
<h1 id="heading-exercise-think-like-laravel-write-like-python">Exercise (Think Like Laravel, Write Like Python)</h1>
<pre><code class="lang-python">products = [
    {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Laptop'</span>, <span class="hljs-string">'price'</span>: <span class="hljs-number">999</span>, <span class="hljs-string">'in_stock'</span>: <span class="hljs-literal">True</span>},
    {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Mouse'</span>, <span class="hljs-string">'price'</span>: <span class="hljs-number">29</span>, <span class="hljs-string">'in_stock'</span>: <span class="hljs-literal">True</span>},
    {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Keyboard'</span>, <span class="hljs-string">'price'</span>: <span class="hljs-number">79</span>, <span class="hljs-string">'in_stock'</span>: <span class="hljs-literal">False</span>},
    {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Monitor'</span>, <span class="hljs-string">'price'</span>: <span class="hljs-number">449</span>, <span class="hljs-string">'in_stock'</span>: <span class="hljs-literal">True</span>},
    {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Webcam'</span>, <span class="hljs-string">'price'</span>: <span class="hljs-number">69</span>, <span class="hljs-string">'in_stock'</span>: <span class="hljs-literal">False</span>},
]
</code></pre>
<p>Try writing:</p>
<ol>
<li><p>All product names</p>
</li>
<li><p>Names of products in stock</p>
</li>
<li><p>Products over $50 and in stock</p>
</li>
<li><p><code>{name: price}</code> lookup</p>
</li>
<li><p>10% discounted prices</p>
</li>
</ol>
<p>If you can solve these comfortably, you're officially thinking in Python.</p>
<hr />
<h1 id="heading-closing-thought">Closing Thought</h1>
<p>Laravel trains you to think in collections, while Python trains you to think in comprehensions. The syntax may look different at first, but the mindset is surprisingly aligned, with clean transformations, readable logic, and expressive code. In the next lesson, we’ll move into Python functions, where things become even more powerful and flexible, and we’ll learn them the Laravel-to-ML way, simple, practical, and developer-focused.</p>
]]></content:encoded></item><item><title><![CDATA[Python Data Structures Simplified for Laravel Developers]]></title><description><![CDATA[Transitioning from PHP to Python for Machine Learning feels a bit like moving from a familiar manual car to an electric one. The controls are in similar places, but the way the engine feels under the hood is fundamentally different.
As Laravel develo...]]></description><link>https://blog.jhaabhishek.com/python-data-structures-simplified-for-laravel-developers</link><guid isPermaLink="true">https://blog.jhaabhishek.com/python-data-structures-simplified-for-laravel-developers</guid><category><![CDATA[Laravel]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[LaraveltoMachineLEarning]]></category><dc:creator><![CDATA[Abhishek Jha]]></dc:creator><pubDate>Wed, 11 Feb 2026 15:47:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1770824434764/033b1b1f-7190-49d5-981a-c435dab3ceef.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Transitioning from PHP to Python for Machine Learning feels a bit like moving from a familiar manual car to an electric one. The controls are in similar places, but the way the engine feels under the hood is fundamentally different.</p>
<p>As Laravel developers, we are spoiled by the PHP array. It’s our everything tool.</p>
<p>Need a list? Array. Need a map? Array. Need a stack? Array.</p>
<p>Python, however, prefers <strong>specialized tools for specialized tasks.</strong> This is the secret to why it handles massive ML datasets so efficiently.</p>
<p>Here is your guide to mastering Python data structures without losing your Laravel mindset.</p>
<hr />
<h2 id="heading-1-lists-your-new-indexed-array">1. Lists: Your New Indexed Array</h2>
<p>In Laravel, when you’re fetching a collection of names, you’re working with an indexed array. In Python, this is a <strong>List</strong>.</p>
<h3 id="heading-the-php-way">The PHP Way</h3>
<pre><code class="lang-php">$frameworks = [<span class="hljs-string">'Laravel'</span>, <span class="hljs-string">'Symfony'</span>, <span class="hljs-string">'CodeIgniter'</span>];
$frameworks[] = <span class="hljs-string">'Lumen'</span>; <span class="hljs-comment">// Push to end</span>
<span class="hljs-keyword">echo</span> $frameworks[<span class="hljs-number">0</span>];     <span class="hljs-comment">// Laravel</span>
</code></pre>
<h3 id="heading-the-python-way">The Python Way</h3>
<pre><code class="lang-python">frameworks = [<span class="hljs-string">'Laravel'</span>, <span class="hljs-string">'Symfony'</span>, <span class="hljs-string">'CodeIgniter'</span>]
frameworks.append(<span class="hljs-string">'FastAPI'</span>) <span class="hljs-comment"># Using a method instead of []</span>
print(frameworks[<span class="hljs-number">0</span>])         <span class="hljs-comment"># Laravel</span>
</code></pre>
<p><strong>The ML Advantage: Slicing</strong></p>
<p>In ML, you often need to "split" your data (e.g., take the first 80% for training). Python makes this incredibly easy compared to <code>array_slice()</code>.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Python "Slicing" syntax: [start:stop]</span>
top_two = frameworks[:<span class="hljs-number">2</span>]  <span class="hljs-comment"># ['Laravel', 'Symfony']</span>
last_one = frameworks[<span class="hljs-number">-1</span>] <span class="hljs-comment"># 'FastAPI' (Negative indexing is a lifesaver!)</span>
</code></pre>
<hr />
<h2 id="heading-2-dicts-the-associative-array">2. Dicts: The Associative Array</h2>
<p>When you’re defining an <code>$user</code> object in a controller, you use an associative array. In Python, we call this a <strong>Dictionary</strong> (or <strong>Dict</strong>).</p>
<h3 id="heading-the-php-way-1">The PHP Way</h3>
<pre><code class="lang-php">$config = [
    <span class="hljs-string">'driver'</span> =&gt; <span class="hljs-string">'mysql'</span>,
    <span class="hljs-string">'host'</span> =&gt; <span class="hljs-string">'127.0.0.1'</span>
];
$driver = $config[<span class="hljs-string">'driver'</span>];
$port = $config[<span class="hljs-string">'port'</span>] ?? <span class="hljs-number">3306</span>; <span class="hljs-comment">// Null coalesce</span>
</code></pre>
<h3 id="heading-the-python-way-1">The Python Way</h3>
<pre><code class="lang-python">config = {
    <span class="hljs-string">'driver'</span>: <span class="hljs-string">'mysql'</span>,
    <span class="hljs-string">'host'</span>: <span class="hljs-string">'127.0.0.1'</span>
}
driver = config[<span class="hljs-string">'driver'</span>]
port = config.get(<span class="hljs-string">'port'</span>, <span class="hljs-number">3306</span>) <span class="hljs-comment"># The "get" method handles missing keys gracefully</span>
</code></pre>
<p><strong>The Human Touch:</strong> In Python, keys are typically strings or numbers. You’ll use these constantly in ML to hold Hyperparameters the settings for your models (like <code>{'learning_rate': 0.01, 'epochs': 10}</code>).</p>
<hr />
<h2 id="heading-3-tuples-the-one-youre-missing">3. Tuples: The One You’re Missing</h2>
<p>This is the one structure that doesn't have a twin in PHP. A <strong>Tuple</strong> is essentially an array that <strong>cannot be changed</strong> once it's born (it's "immutable").</p>
<h3 id="heading-why-would-you-want-that">Why would you want that?</h3>
<p>Imagine you have an RGB color for a brand or geographic coordinates for a store. You don't want your code to accidentally change the Latitude halfway through a calculation.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Defined with parentheses</span>
coordinates = (<span class="hljs-number">34.0522</span>, <span class="hljs-number">-118.2437</span>)

<span class="hljs-comment"># This will throw an error! </span>
<span class="hljs-comment"># coordinates[0] = 35.0</span>
</code></pre>
<p><strong>Pythonic "Unpacking":</strong></p>
<p>You know how we use <code>list()</code> or <code>[]</code> In PHP, to destructure? Python does this natively and beautifully.</p>
<pre><code class="lang-php"><span class="hljs-comment">// PHP Destructuring</span>
[$lat, $long] = [<span class="hljs-number">34.0522</span>, <span class="hljs-number">-118.2437</span>];
</code></pre>
<pre><code class="lang-python"><span class="hljs-comment"># Python Unpacking</span>
lat, long = coordinates
print(<span class="hljs-string">f"Lat: <span class="hljs-subst">{lat}</span>, Long: <span class="hljs-subst">{long}</span>"</span>)
</code></pre>
<hr />
<h2 id="heading-the-laravel-to-python-cheat-sheet">The "Laravel to Python" Cheat Sheet</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Task</strong></td><td><strong>Laravel (PHP)</strong></td><td><strong>Python</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Count items</strong></td><td><code>count($items)</code></td><td><code>len(items)</code></td></tr>
<tr>
<td><strong>Check for key</strong></td><td><code>array_key_exists('k', $arr)</code></td><td><code>'k' in items</code></td></tr>
<tr>
<td><strong>Merge data</strong></td><td><code>array_merge($a, $b)</code></td><td><code>{**a, **b}</code> (for dicts)</td></tr>
<tr>
<td><strong>Get all keys</strong></td><td><code>array_keys($arr)</code></td><td><code>items.keys()</code></td></tr>
<tr>
<td><strong>Looping</strong></td><td><code>foreach($arr as $k =&gt; $v)</code></td><td><code>for k, v in items.items():</code></td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-exercise-the-laravel-config-challenge">Exercise: The "Laravel Config" Challenge</h2>
<p>To get these into your muscle memory, try this:</p>
<ol>
<li><p>Create a <strong>Dict</strong> named <code>app_settings</code> containing a <code>name</code>, <code>env</code>, and a <strong>List</strong> of <code>providers</code>.</p>
</li>
<li><p>Add a new provider to the list.</p>
</li>
<li><p>Use <code>.get()</code> to try to print a <code>version</code> key that doesn't exist yet, providing <code>1.0</code> as a default.</p>
</li>
<li><p>Create a <strong>Tuple</strong> for your database credentials <code>(host, port, user)</code> and unpack them into three separate variables.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Laravel to ML Roadmap]]></title><description><![CDATA[Think of this roadmap like a road you’re walking, not a course you’re rushing through.
You start where you already are, building Laravel apps, handling requests, and working with data. The first few checkpoints are simple: Python basics and data hand...]]></description><link>https://blog.jhaabhishek.com/laravel-to-ml-roadmap</link><guid isPermaLink="true">https://blog.jhaabhishek.com/laravel-to-ml-roadmap</guid><category><![CDATA[LaraveltoMachineLEarning]]></category><category><![CDATA[Laravel]]></category><category><![CDATA[Machine Learning]]></category><dc:creator><![CDATA[Abhishek Jha]]></dc:creator><pubDate>Tue, 10 Feb 2026 16:42:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1770742617585/c04fe682-e658-4415-8c3c-f3517e00b285.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Think of this roadmap like a <strong>road you’re walking</strong>, not a course you’re rushing through.</p>
<p>You start where you already are, building Laravel apps, handling requests, and working with data. The first few checkpoints are simple: Python basics and data handling. Nothing fancy. Lists feel like arrays, DataFrames feel like collections. You’re not learning ML, yet you’re just getting comfortable with the tools the ML world uses.</p>
<p>As you move forward on the path, you hit NumPy, Pandas, and visualization. This is the part where things start making sense. You stop seeing data as rows in a table and start seeing patterns. You clean messy data, join datasets, and draw charts to understand what’s really going on. Most of the time here feels like backend work, just with larger datasets and a bit more math.</p>
<p>Near the end of the road, you finally reach the ML part: algorithms, training, testing, and evaluation. By now, they don’t feel scary. They feel logical. You try them in one real project, end-to-end, and suddenly ML is no longer a buzzword; it’s just another system you understand. Past this point, the road opens up to deeper areas like NLP, deep learning, or MLOps.</p>
<p>That’s the idea behind the roadmap.<br />Not switching careers. Not chasing hype.<br />Just one developer adding a new skill, step by step.</p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Laravel Naming Conventions Guide]]></title><description><![CDATA[Laravel is often referred to as a magical framework, and for good reason. When you follow its default naming conventions, it feels like Laravel can read your mind. Things work without you having to write extra code or constantly configure every littl...]]></description><link>https://blog.jhaabhishek.com/laravel-naming-conventions-guide</link><guid isPermaLink="true">https://blog.jhaabhishek.com/laravel-naming-conventions-guide</guid><category><![CDATA[Laravel]]></category><category><![CDATA[#namingconvention]]></category><category><![CDATA[Laraveldevelopment ]]></category><category><![CDATA[laravelframework]]></category><dc:creator><![CDATA[Abhishek Jha]]></dc:creator><pubDate>Fri, 15 Aug 2025 14:07:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1755265143605/d13d5ce2-f15d-42b0-8103-1f71c2e9705d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Laravel is often referred to as a <strong>magical framework</strong>, and for good reason. When you follow its default naming conventions, it feels like Laravel can read your mind. Things work without you having to write extra code or constantly configure every little detail. Instead of manually hardcoding file names, table names, or relationships, you simply follow Laravel’s naming conventions and let the framework handle the rest.</p>
<p><strong>Why stick to Laravel’s naming conventions?</strong></p>
<ol>
<li><p><strong>Less hassle</strong>: Laravel figures out models, tables, and relationships for you.</p>
</li>
<li><p><strong>Cleaner, friendlier code</strong>: Easy to read today and months later.</p>
</li>
<li><p><strong>Fewer silly bugs</strong>: No more “Oops, I named it differently in the code and the database.”</p>
</li>
<li><p><strong>Faster work</strong>: Skip the boring configuration steps and get straight to building features.</p>
</li>
<li><p><strong>Team harmony</strong>: Everyone instantly understands the structure without a long onboarding session.</p>
</li>
</ol>
<p>In this blog, we will explore naming conventions for:</p>
<ol>
<li><p>Models</p>
</li>
<li><p>Controllers</p>
</li>
<li><p>Migrations</p>
</li>
<li><p>CSS files</p>
</li>
<li><p>JavaScript files</p>
</li>
<li><p>Blade templates</p>
</li>
<li><p>Models, Tables &amp; Relationships</p>
</li>
</ol>
<h3 id="heading-1-models"><strong>1. Models</strong></h3>
<p>Models in Laravel represent your database tables and are stored in <code>app/Models</code>.</p>
<p><strong>Convention:</strong></p>
<ul>
<li><p><strong>Singular</strong> name</p>
</li>
<li><p><strong>PascalCase</strong> (StudlyCase)</p>
</li>
<li><p>No underscores or hyphens</p>
</li>
</ul>
<p>✅ <strong>Examples:</strong></p>
<pre><code class="lang-php"><span class="hljs-comment">// Good</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span> </span>{}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OrderDetail</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span> </span>{}

<span class="hljs-comment">// Bad</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Users</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span> </span>{}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">order_detail</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span> </span>{}
</code></pre>
<p>📌 <strong>Why singular?</strong><br />Each model represents <strong>one record</strong> in the table (one <code>User</code>, one <code>Order</code>).</p>
<hr />
<h3 id="heading-2-controllers"><strong>2. Controllers</strong></h3>
<p>Controllers handle your application logic and live in <code>app/Http/Controllers</code>.</p>
<p><strong>Convention:</strong></p>
<ul>
<li><p><strong>PascalCase</strong></p>
</li>
<li><p>Always end with <code>Controller</code></p>
</li>
<li><p>Group logically based on purpose</p>
</li>
</ul>
<p>✅ <strong>Examples:</strong></p>
<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-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OrderDetailController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span> </span>{}
</code></pre>
<p>🚫 <strong>Bad:</strong></p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">usercontroller</span> </span>{}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Order_Detail</span> </span>{}
</code></pre>
<p>📌 <strong>Tip:</strong> Use:</p>
<pre><code class="lang-php">php artisan make:controller UserController
</code></pre>
<p>to auto-follow conventions.</p>
<hr />
<h3 id="heading-3-migrations"><strong>3. Migrations</strong></h3>
<p>Migrations define your database structure and are stored in <code>database/migrations</code>.</p>
<p><strong>Convention:</strong></p>
<ul>
<li><p><strong>snake_case</strong></p>
</li>
<li><p>Words separated by underscores</p>
</li>
<li><p>Describe the action + table name</p>
</li>
<li><p>Timestamp prefix auto-generated</p>
</li>
</ul>
<p>✅ <strong>Examples:</strong></p>
<pre><code class="lang-php"><span class="hljs-number">2025</span>_08_15_120000_create_users_table.php
<span class="hljs-number">2025</span>_08_15_120100_add_status_to_orders_table.php
</code></pre>
<p>📌 <strong>Tip:</strong></p>
<pre><code class="lang-php">php artisan make:migration create_users_table
php artisan make:migration add_status_to_orders_table --table=orders
</code></pre>
<hr />
<h3 id="heading-4-css-files"><strong>4. CSS Files</strong></h3>
<p>Usually stored in <code>public/css</code> or <code>resources/css</code>.</p>
<p><strong>Convention:</strong></p>
<ul>
<li><p>Lowercase</p>
</li>
<li><p>Hyphen-separated</p>
</li>
<li><p>Descriptive names</p>
</li>
</ul>
<p>✅ <strong>Examples:</strong></p>
<pre><code class="lang-php">main.css
admin-dashboard.css
user-profile.css
</code></pre>
<hr />
<h3 id="heading-5-javascript-files"><strong>5. JavaScript Files</strong></h3>
<p>Stored in <code>resources/js</code> (for build tools) or <code>public/js</code>.</p>
<p><strong>Convention:</strong></p>
<ul>
<li><p>Lowercase</p>
</li>
<li><p>Hyphen-separated</p>
</li>
<li><p>Use action-oriented names if script is specific</p>
</li>
</ul>
<p>✅ <strong>Examples:</strong></p>
<pre><code class="lang-javascript">app.js
form-validation.js
user-profile.js
</code></pre>
<hr />
<h3 id="heading-6-blade-templates"><strong>6. Blade Templates</strong></h3>
<p>Stored in <code>resources/views</code>.</p>
<p><strong>Convention:</strong></p>
<ul>
<li><p>Lowercase</p>
</li>
<li><p>Hyphen-separated</p>
</li>
<li><p>Use folders for grouping</p>
</li>
<li><p>No underscores</p>
</li>
</ul>
<p>✅ <strong>Examples:</strong></p>
<pre><code class="lang-php">resources/views/auth/login.blade.php
resources/views/admin/dashboard.blade.php
resources/views/user/profile.blade.php
</code></pre>
<p>📌 <strong>Tip:</strong> Use dots in view calls:</p>
<pre><code class="lang-php"><span class="hljs-keyword">return</span> view(<span class="hljs-string">'admin.dashboard'</span>);
</code></pre>
<hr />
<h3 id="heading-7-models-tables-amp-relationships"><strong>7. Models, Tables &amp; Relationships</strong></h3>
<p>Laravel’s <strong>Eloquent ORM</strong> has default rules for naming tables and relationships.</p>
<h4 id="heading-models-amp-tables"><strong>Models &amp; Tables</strong></h4>
<ul>
<li><p><strong>Models:</strong> Singular, <code>PascalCase</code></p>
</li>
<li><p><strong>Tables:</strong> Plural, <code>snake_case</code></p>
</li>
</ul>
<p>✅ <strong>Examples:</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Model</td><td>Table Name</td></tr>
</thead>
<tbody>
<tr>
<td><code>User</code></td><td><code>users</code></td></tr>
<tr>
<td><code>OrderDetail</code></td><td><code>order_details</code></td></tr>
<tr>
<td><code>ProductCategory</code></td><td><code>product_categories</code></td></tr>
</tbody>
</table>
</div><p>If your table doesn’t match the convention, define it:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserInfo</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span> </span>{
    <span class="hljs-keyword">protected</span> $table = <span class="hljs-string">'user_information'</span>;
}
</code></pre>
<hr />
<h4 id="heading-relationships"><strong>Relationships</strong></h4>
<p>Eloquent relationships also follow specific naming:</p>
<p><strong>One-to-One / One-to-Many</strong></p>
<ul>
<li>Method name: <strong>singular</strong> for one-to-one, <strong>plural</strong> for one-to-many</li>
</ul>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</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">profile</span>(<span class="hljs-params"></span>) </span>{  <span class="hljs-comment">// one-to-one</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;hasOne(Profile::class);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">posts</span>(<span class="hljs-params"></span>) </span>{    <span class="hljs-comment">// one-to-many</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;hasMany(Post::class);
    }
}
</code></pre>
<p><strong>Belongs To</strong></p>
<ul>
<li>Method name: <strong>singular</strong> (refers to parent)</li>
</ul>
<pre><code class="lang-javascript"><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>{
    public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">user</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> $this-&gt;belongsTo(User::<span class="hljs-class"><span class="hljs-keyword">class</span>)</span>;
    }
}
</code></pre>
<p><strong>Many-to-Many</strong></p>
<ul>
<li><p>Pivot table: <strong>alphabetical order</strong>, plural, snake_case</p>
</li>
<li><p>Method name: <strong>plural</strong></p>
</li>
</ul>
<pre><code class="lang-php"><span class="hljs-comment">// Table: role_user (alphabetical: role before user)</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</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">roles</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;belongsToMany(Role::class);
    }
}
</code></pre>
<p>✅ <strong>Pivot Table Examples:</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Models</td><td>Pivot Table</td></tr>
</thead>
<tbody>
<tr>
<td><code>User</code> &amp; <code>Role</code></td><td><code>role_user</code></td></tr>
<tr>
<td><code>Post</code> &amp; <code>Tag</code></td><td><code>post_tag</code></td></tr>
</tbody>
</table>
</div><hr />
<h4 id="heading-primary-and-foreign-key-naming-conventions-in-relationships"><strong>Primary and Foreign Key Naming Conventions in Relationships</strong></h4>
<p>In Laravel, following the right primary and foreign key naming patterns ensures that Eloquent relationships work without extra configuration.</p>
<ul>
<li><p><strong>Primary Keys</strong> – Each table should have an <code>id</code> column as its primary key.</p>
</li>
<li><p><strong>One-to-Many (O2M)</strong> – The foreign key should be the <strong>singular form</strong> of the related model’s name followed by <code>_id</code>.</p>
<ul>
<li>Example: If a <code>Post</code> belongs to a <code>User</code>, the <code>posts</code> table should have <code>user_id</code>.</li>
</ul>
</li>
<li><p><strong>Many-to-Many (M2M)</strong> – Use a <strong>pivot table</strong> named with both related model names in <strong>singular, snake_case</strong>, arranged in <strong>alphabetical order</strong>, with each containing its foreign key in the same pattern.</p>
<ul>
<li><p>Example: For <code>User</code> and <code>Role</code> models, pivot table → <code>role_user</code></p>
<ul>
<li>Columns: <code>role_id</code>, <code>user_id</code></li>
</ul>
</li>
</ul>
</li>
</ul>
<p>By sticking to these naming rules, you can define relationships without specifying custom keys, letting Laravel automatically link your models.</p>
<hr />
<h3 id="heading-final-thoughts"><strong>Final Thoughts</strong></h3>
<p>Following these conventions:</p>
<ul>
<li><p>Makes your Laravel codebase self-explanatory</p>
</li>
<li><p>Allows Laravel’s “magic” features to work without extra configuration</p>
</li>
<li><p>Keeps large projects clean and maintainable</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Express Js Middleware]]></title><description><![CDATA[Let's understand it in a short story, suppose you want to issue a book from a library then you have to go through some checkpoints, so consider those as middleware. First, you will be checked to know whether you are authenticated to access college pr...]]></description><link>https://blog.jhaabhishek.com/express-js-middleware</link><guid isPermaLink="true">https://blog.jhaabhishek.com/express-js-middleware</guid><category><![CDATA[Express]]></category><category><![CDATA[Express.js]]></category><category><![CDATA[Middleware]]></category><dc:creator><![CDATA[Abhishek Jha]]></dc:creator><pubDate>Tue, 06 Aug 2024 16:00:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722947145242/d73002ee-696c-4fa5-bbc3-aaa914150fa4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Let's understand it in a short story, suppose you want to issue a book from a library then you have to go through some checkpoints, so consider those as middleware. First, you will be checked to know whether you are <strong>authenticated</strong> to access college premises, and then the librarian will check your <strong>authorization</strong> by your library card after that she will <strong>log</strong> your request and you will get your book, This is where the middleware plays an important role.</p>
<p><strong>Middleware</strong></p>
<p>Defining middleware is very easy in Express JS it takes three parameters <code>req</code>, <code>res</code> and <code>next</code> and only in error handling middleware we have one extra parameter that is <code>err</code> .</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/** req object represents the HTTP request made by the client to the server */</span>
<span class="hljs-comment">/** res object represents the HTTP response that the server will send back to the client */</span>
<span class="hljs-comment">/** next  function is used to pass control to the next middleware function in the stack */</span>
app.use(<span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> { });
</code></pre>
<p><strong>Types of middlewares</strong></p>
<p>As per the above example we can say middleware has many purposes to serve, we can categorize it into four types, Application level, Route level, Error handling, Built-in, and Third-party middleware</p>
<ol>
<li><p><strong>Application level</strong><br /> As we have seen in the above example if you want to enter the college premises, you will need an ID card for authentication so we can use the application-level middleware to check for the authenticated requests.</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">/**Importing the express Js */</span>

 <span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);

 <span class="hljs-comment">/** Initializing the express application */</span>

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

 <span class="hljs-comment">/**Applying application level middleware */</span>

 app.use(<span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> {
     <span class="hljs-comment">/**Logic to check user is authenticated or not */</span>
     next()
 });
</code></pre>
</li>
<li><p><strong>Route level</strong></p>
<p> In the library, some sections are reserved for the college staff, so some areas are inaccessible even if you have an ID card(Authenticated user). To achieve this in express Js we need to secure those routes from other users to achieve this we will use Route level middleware.</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">/** Importing the express Js */</span>
 <span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);

 <span class="hljs-comment">/** Creating a new instance of router. */</span>
 <span class="hljs-keyword">const</span> router = express.Router();

 <span class="hljs-comment">/**
 * Route level middleware are bound to an instance of express.Router().
 */</span>
 router.use(<span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> {
     <span class="hljs-comment">/**Logic to validate whether a user is staff or not */</span>
     next()
 });
</code></pre>
<p> There are a few more examples of route-level middleware that will help us</p>
<p> drill down to use middleware more effectively. We can say that we want to add a validation that a user can only issue a book of the course he/she has opted for to achieve this in express we will use the below code.</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">/**
 * Middleware that will be applied on /books/stream/:streamName and /books/stream/:streamName/zyz
 */</span>
 router.use(<span class="hljs-string">'/books/stream/:streamName'</span>,<span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> {
     <span class="hljs-comment">/**Logic to validate stream based on stream name and user */</span>
     next();
 });
</code></pre>
</li>
<li><p><strong>Error handling</strong></p>
<p> Error-logging middleware can be easily identified by an extra parameter in the middleware function, it is one of the default features provided by Express Js. We can use this feature whenever we have to throw an error.</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">/**Registering a middleware to catch and log error and return 500 to users*/</span>
 app.use(<span class="hljs-function">(<span class="hljs-params">err, req, res, next</span>) =&gt;</span> {
   <span class="hljs-built_in">console</span>.error(err.stack);
   res.status(<span class="hljs-number">500</span>).send(<span class="hljs-string">'Something went wron'</span>);
 })
</code></pre>
</li>
<li><p><strong>Built-in</strong></p>
<p> Express provides several built-in middleware functions that help handle common tasks in web development, we will see a few examples of built-in middleware.</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">/*
 * Used to convert JSON data in request to Javascript object and can be accesed by req.body
 * Used when Content-Type is application/json mainly in REST API's
 */</span>
 app.use(express.json());
</code></pre>
<pre><code class="lang-javascript"> <span class="hljs-comment">/**
 * Used when user submit a web form with Content type application/x-www-form-urlencoded
 * To convert the urlencoded data into Javascript object.
 */</span>
 app.use(express.urlencoded({ <span class="hljs-attr">extended</span>: <span class="hljs-literal">true</span> }));
</code></pre>
<pre><code class="lang-javascript"> <span class="hljs-comment">/**
 * Used to serve static files (HTML, CSS, JS, Images)from the public folder.
 * You can sepecify any other folder of you choice also.
 */</span>
 app.use(express.static(<span class="hljs-string">'public'</span>));
</code></pre>
</li>
<li><p><strong>Third-party</strong></p>
<p> There are many library available to simplify web development, so we don’t have to write everything from scratch. Instead, we can use these features by simply installing them with npm. We will see to most common example of third-party middleware.</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">/** CORS Middleware */</span>
 <span class="hljs-comment">/** Allows your server to handle requests from different origins, which is essential for enabling Cross-Origin Resource Sharing (CORS). */</span> 
 <span class="hljs-comment">/** npm install cors */</span>
 <span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
 <span class="hljs-keyword">const</span> cors = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cors'</span>);
 <span class="hljs-keyword">const</span> app = express();

 <span class="hljs-comment">/** Use CORS middleware to allow requests from any origin */</span>
 app.use(cors());

 app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
   res.send(<span class="hljs-string">'CORS is enabled for all origins!'</span>);
 });
</code></pre>
<pre><code class="lang-javascript"> <span class="hljs-comment">/** Parses cookies attached to the client request object and makes them available via req.cookies.*/</span>
 <span class="hljs-comment">/** Cookie parser middleware */</span>
 <span class="hljs-comment">/** npm install cookie-parser */</span>
 <span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
 <span class="hljs-keyword">const</span> app = express();
 <span class="hljs-keyword">const</span> cookieParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cookie-parser'</span>);
 <span class="hljs-comment">/** Adding cookieParser middleware */</span>
 app.use(cookieParser());
</code></pre>
</li>
</ol>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In summary, middleware in Express.js acts like checkpoints in a library, performing various tasks to ensure smooth operations. From application-level checks like authentication to route-level validation and error handling, middleware helps manage requests and responses efficiently. Built-in middleware such as <code>express.json()</code> and <code>express.static()</code> streamline common tasks, while third-party middleware like <code>cors</code> and <code>cookie-parser</code> enhance functionality with minimal setup. By understanding and utilizing these middleware types, you can build robust, well-organized web applications that handle various scenarios seamlessly.</p>
]]></content:encoded></item><item><title><![CDATA[Routing in Express Js]]></title><description><![CDATA[In this article, we will learn about routing in Express Js that we will use whether we are developing REST API or full-stack applications. Let's understand, why we need routing and how it will help us to manage application code better and also help i...]]></description><link>https://blog.jhaabhishek.com/routing-in-express-js</link><guid isPermaLink="true">https://blog.jhaabhishek.com/routing-in-express-js</guid><category><![CDATA[Express.js]]></category><category><![CDATA[Routing in Express JS]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Express]]></category><dc:creator><![CDATA[Abhishek Jha]]></dc:creator><pubDate>Thu, 01 Aug 2024 05:51:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722491199401/b5b667f1-dfdd-44fc-9bbe-d35db1b3b2f4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, we will learn about routing in Express Js that we will use whether we are developing REST API or full-stack applications. Let's understand, why we need routing and how it will help us to manage application code better and also help in implementing coding principles like <a target="_blank" href="https://www.digitalocean.com/community/tutorials/what-is-dry-development">DRY</a> and <a target="_blank" href="https://www.digitalocean.com/community/conceptual-articles/s-o-l-i-d-the-first-five-principles-of-object-oriented-design">SOLID</a>.</p>
<h3 id="heading-what-is-routing">What is Routing?</h3>
<p>We access anything in any application using some endpoints(URL) and whenever we make any request some code on the server executes to complete our request and give us the response. If we divide it into parts we have two things one is the endpoint and the second is the code that executes on the server, this is where routing helps us to map our endpoints with the specific piece of functionality from our application.</p>
<h3 id="heading-why-do-we-need-routing">Why do we need Routing?</h3>
<p>Here's why routing is necessary.</p>
<ol>
<li><p><strong>URL Mapping</strong></p>
<p> Routing allows you to map URLs to specific functions or handlers within your application.</p>
</li>
<li><p><strong>Separation of Concerns</strong></p>
<p> It helps to separate different parts of the application from one another like authentication, authorization, admin, and users.</p>
</li>
<li><p><strong>Dynamic URL Handling</strong></p>
<p> A route <code>/users/:id</code> can dynamically match any user ID and allow your application to fetch or process data for that specific user.</p>
</li>
<li><p><strong>Implementing RESTful APIs</strong></p>
</li>
</ol>
<p>In RESTful API design, routing is responsible for mapping HTTP methods (GET, POST, PUT, PATCH, DELETE) to actions on resources.</p>
<ol start="5">
<li><p><strong>Middleware Integration</strong></p>
<p> It is a function that runs before the final request handler to process or modify the request or response in an application.</p>
</li>
<li><p><strong>Error Handling</strong></p>
<p> With routing, you can define specific routes to handle errors or exceptions. For instance, you can create a catch-all route for 404 errors to handle cases where users navigate to a non-existent page.</p>
</li>
<li><p><strong>Modular Code Structure</strong></p>
<p> Routing allows you to break your application into smaller, more manageable modules or files.</p>
</li>
</ol>
<h3 id="heading-http-methods">HTTP Methods</h3>
<p>There are several HTTP methods, but the most commonly used ones are:</p>
<ol>
<li><p><strong>GET</strong> To retrieve resources from the server</p>
</li>
<li><p><strong>POST</strong> Submit to create new resources on the server like registering a new user.</p>
</li>
<li><p><strong>PUT</strong> To replace any resource from the server like replacing any image with a new</p>
</li>
<li><p><strong>PATCH</strong>: To update resources on the server like updating a user's email address.</p>
</li>
<li><p><strong>DELETE</strong> To delete resources from the server.</p>
</li>
</ol>
<p><strong>How to declare routes</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">/** Importing the express Js */</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);

<span class="hljs-comment">/** Creating a new instance of router. */</span>
<span class="hljs-keyword">const</span> router = express.Router();
<span class="hljs-comment">/**
 * The first is method which we will choose according to our need.
 * The first parameter is the url we want to assign that functionality.
 * Second parameter is a callback function that will be executed when user hit that URL
 * Callback function will have two parameter that is request,response.
 */</span>

router.get(<span class="hljs-string">"/url"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {});
</code></pre>
<p>As of now, we have gained a rough idea of routing and the purpose with methods, now we will see how Express Js helps with <strong>Routing</strong>. Express Js has a built-in routing mechanism we can access using the code below.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/** Importing the express Js */</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);

<span class="hljs-comment">/** Creating a new instance of router. */</span>
<span class="hljs-keyword">const</span> router = express.Router();

<span class="hljs-comment">/**
 * GET
 * URI /list-of-tasks
 * To get the list of tasks to do
 */</span>
router.get(<span class="hljs-string">"/list-of-tasks"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> tasks = [
    { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"Task 1"</span>, <span class="hljs-attr">description</span>: <span class="hljs-string">"This is the first task"</span> },
    { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"Task 2"</span>, <span class="hljs-attr">description</span>: <span class="hljs-string">"This is the second task"</span> },
    { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"Task 3"</span>, <span class="hljs-attr">description</span>: <span class="hljs-string">"This is the third task"</span> },
  ];
  res.json(tasks);
});
<span class="hljs-comment">/** Exporting routes to register in the app to make it available to accept request and return response */</span>
<span class="hljs-built_in">module</span>.exports = router;
</code></pre>
<p>We will see how and when to use different HTTP methods for that we will do a basic CRUD and to get the request we will install a new package to parse the request body. Please run the command to install the package <code>npm install body-parser</code> after that create a file routes.js in the project folder(express-01) and paste the below code in <code>main.js</code> file that we have created in the last article.</p>
<p><strong>NOTE:</strong> Don't worry about the HTML we will see in the upcoming article for handling views.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/**Importing the express Js */</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);

<span class="hljs-comment">/** Initializing the express application */</span>
<span class="hljs-keyword">const</span> app = express();
<span class="hljs-keyword">const</span> bodyParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">'body-parser'</span>);

app.use(bodyParser.urlencoded({ <span class="hljs-attr">extended</span>: <span class="hljs-literal">true</span> }));

<span class="hljs-comment">/** Register the route to accept the get request */</span>
app.get(<span class="hljs-string">'/'</span>,<span class="hljs-function">(<span class="hljs-params">req,res,next</span>) =&gt;</span> {
    res.send(<span class="hljs-string">'Hello World'</span>);
});

<span class="hljs-keyword">const</span> customRoutes = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./routes'</span>);

app.use(customRoutes);

<span class="hljs-comment">/** Create server and start listing on the port of your choice */</span>
app.listen(<span class="hljs-number">3000</span>);
</code></pre>
<p>Paste the below code into the <code>routes.js</code> file</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/** Importing the express Js */</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);

<span class="hljs-comment">/** Creating a new instance of router. */</span>
<span class="hljs-keyword">const</span> router = express.Router();

<span class="hljs-keyword">const</span> tasks = [
    { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"Task 1"</span>, <span class="hljs-attr">description</span>: <span class="hljs-string">"This is the first task"</span> },
    { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"Task 2"</span>, <span class="hljs-attr">description</span>: <span class="hljs-string">"This is the second task"</span> },
    { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"Task 3"</span>, <span class="hljs-attr">description</span>: <span class="hljs-string">"This is the third task"</span> },
];

<span class="hljs-comment">/**
 * GET
 * URI /list-of-tasks
 * To get the list of tasks to do
 */</span>
router.get(<span class="hljs-string">"/list-of-tasks"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    res.send(
        <span class="hljs-string">`&lt;body style="font-family: Arial, sans-serif; margin: 20px;"&gt;

            &lt;h1 style="text-align: center;"&gt;Task List&lt;/h1&gt;
            &lt;div style="text-align: center; margin-bottom: 20px;"&gt;
                &lt;a href="/add-task" style="display: inline-block; background-color: #007BFF; color: white; text-align: center; border: none; border-radius: 5px; padding: 10px 20px; cursor: pointer; text-decoration: none; font-size: 16px; margin-bottom: 20px;"&gt;
                    Add New Task
                &lt;/a&gt;
            &lt;/div&gt;

            &lt;ul style="list-style-type: none; padding: 0; max-width: 600px; margin: 0 auto;"&gt;`</span>
                + tasks.map(<span class="hljs-function">(<span class="hljs-params">task</span>) =&gt;</span> {
                    <span class="hljs-keyword">return</span>  <span class="hljs-string">`&lt;li style="border: 1px solid #ddd; border-radius: 5px; padding: 10px; margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center;"&gt;
                    &lt;div style="flex: 1;"&gt;
                        &lt;h2 style="margin: 0; font-size: 18px; color: #333;"&gt;<span class="hljs-subst">${task.name}</span>&lt;/h2&gt;
                        &lt;p style="margin: 5px 0 0; color: #666;"&gt;<span class="hljs-subst">${task.description}</span>&lt;/p&gt;
                    &lt;/div&gt;
                    &lt;a href="/edit-task/<span class="hljs-subst">${task.id}</span>" style="display: inline-block; background-color: #4CAF50; color: white; text-align: center; border: none; border-radius: 5px; padding: 8px 16px; cursor: pointer; text-decoration: none;"&gt;
                        Edit
                    &lt;/a&gt;
                    &lt;form action="/delete-task/<span class="hljs-subst">${task.id}</span>" method="POST" style="margin-bottom:0;"&gt;
                        &lt;button type="submit" style="display: inline-block; background-color: #9e0132; color: white; text-align: center; border: none; border-radius: 5px; padding: 8px 16px; cursor: pointer;  margin-left:10px;"&gt;Delete&lt;/button&gt;
                    &lt;/form&gt;

                &lt;/li&gt;`</span>;
                }).join(<span class="hljs-string">""</span>)+<span class="hljs-string">`
            &lt;/ul&gt;

        &lt;/body&gt;`</span>
    );  
});

<span class="hljs-comment">/**
 * GET
 * URI /add-task
 * To get the list of tasks to do
 */</span>
router.get(<span class="hljs-string">"/add-task"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    res.send(<span class="hljs-string">` &lt;body style="display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0;"&gt;
    &lt;div style="text-align: center;"&gt;
        &lt;h1&gt;Add New Task&lt;/h1&gt;

        &lt;form action="/submit-task" method="post" style="display: inline-block; text-align: left;"&gt;
            &lt;div style="margin-bottom: 15px;"&gt;
                &lt;label for="name" style="display: block; margin-bottom: 5px;"&gt;Name:&lt;/label&gt;
                &lt;input type="text" id="name" name="name" required style="width: 100%; padding: 8px; box-sizing: border-box;"&gt;
            &lt;/div&gt;
            &lt;div style="margin-bottom: 15px;"&gt;
                &lt;label for="description" style="display: block; margin-bottom: 5px;"&gt;Description:&lt;/label&gt;
                &lt;textarea id="description" name="description" rows="4" cols="50" required style="width: 100%; padding: 8px; box-sizing: border-box;"&gt;&lt;/textarea&gt;
            &lt;/div&gt;
            &lt;button type="submit" style="padding: 10px 20px; font-size: 16px;"&gt;Submit&lt;/button&gt;
        &lt;/form&gt;
    &lt;/div&gt;
&lt;/body&gt;`</span>);
res.end();
});

<span class="hljs-comment">/**
 * POST
 * URI /add-tasks
 * To add new task.
 */</span>
router.post(<span class="hljs-string">'/submit-task'</span>,<span class="hljs-function">(<span class="hljs-params">req,res</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> newTask = {
        <span class="hljs-attr">id</span>: tasks.length + <span class="hljs-number">1</span>,
        <span class="hljs-attr">name</span>: req.body.name,
        <span class="hljs-attr">description</span>: req.body.description,
    }
    tasks.push(newTask);
    res.redirect(<span class="hljs-string">'/list-of-tasks'</span>);

});

<span class="hljs-comment">/**
 * GET 
 * URI /edit-task/:id
 * To get an edit form to update the task
 */</span>
router.get(<span class="hljs-string">"/edit-task/:id"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> taskId = req.params.id;
    <span class="hljs-keyword">const</span> task = tasks.find(<span class="hljs-function">(<span class="hljs-params">task</span>) =&gt;</span> task.id === <span class="hljs-built_in">parseInt</span>(taskId));
    <span class="hljs-keyword">if</span> (!task) {
        res.status(<span class="hljs-number">404</span>).send(<span class="hljs-string">"Task not found"</span>);
        <span class="hljs-keyword">return</span>;
    }

    res.send(<span class="hljs-string">` &lt;body style="display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0;"&gt;
    &lt;div style="text-align: center;"&gt;
        &lt;h1&gt;Update Task&lt;/h1&gt;

        &lt;form action="/update-task/<span class="hljs-subst">${task.id}</span>" method="post" style="display: inline-block; text-align: left;"&gt;
            &lt;div style="margin-bottom: 15px;"&gt;
                &lt;label for="name" style="display: block; margin-bottom: 5px;"&gt;Name:&lt;/label&gt;
                &lt;input type="text" id="name" name="name" required style="width: 100%; padding: 8px; box-sizing: border-box;" value="<span class="hljs-subst">${task.name}</span>"&gt;
            &lt;/div&gt;
            &lt;div style="margin-bottom: 15px;"&gt;
                &lt;label for="description" style="display: block; margin-bottom: 5px;"&gt;Description:&lt;/label&gt;
                &lt;textarea id="description" name="description" rows="4" cols="50" required style="width: 100%; padding: 8px; box-sizing: border-box;" value="<span class="hljs-subst">${task.description}</span>"&gt;<span class="hljs-subst">${task.description}</span>&lt;/textarea&gt;
            &lt;/div&gt;
            &lt;button type="submit" style="padding: 10px 20px; font-size: 16px;"&gt;Submit&lt;/button&gt;
        &lt;/form&gt;
    &lt;/div&gt;
&lt;/body&gt;`</span>);
});

<span class="hljs-comment">/**
 * POST
 * URI /update-task/:id
 * To update task based on id
 */</span>
router.post(<span class="hljs-string">"/update-task/:id"</span>,<span class="hljs-function">(<span class="hljs-params">req,res</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> taskId = req.params.id;
    <span class="hljs-keyword">const</span> task = tasks.find(<span class="hljs-function">(<span class="hljs-params">task</span>) =&gt;</span> task.id === <span class="hljs-built_in">parseInt</span>(taskId));
    <span class="hljs-keyword">if</span> (!task) {
        res.status(<span class="hljs-number">404</span>).send(<span class="hljs-string">"Task not found"</span>);
        <span class="hljs-keyword">return</span>;
    }
    <span class="hljs-keyword">const</span> newTask = {
        <span class="hljs-attr">id</span>: task.id,
        <span class="hljs-attr">name</span>: req.body.name,
        <span class="hljs-attr">description</span>: req.body.description
    }
    <span class="hljs-built_in">Object</span>.assign(task, newTask);
    res.redirect(<span class="hljs-string">'/list-of-tasks'</span>);
});

<span class="hljs-comment">/**
 * POST
 * URI delete-task/:id
 * To delete the task based on id
 */</span>
router.post(<span class="hljs-string">'/delete-task/:id'</span>,<span class="hljs-function">(<span class="hljs-params">req,res</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> taskId = req.params.id;
    <span class="hljs-keyword">const</span> task = tasks.find(<span class="hljs-function">(<span class="hljs-params">task</span>) =&gt;</span> task.id === <span class="hljs-built_in">parseInt</span>(taskId));

    <span class="hljs-keyword">if</span> (!task) {
        res.status(<span class="hljs-number">404</span>).send(<span class="hljs-string">"Task not found"</span>);
        <span class="hljs-keyword">return</span>;
    }
    <span class="hljs-keyword">const</span> index = tasks.indexOf(task);
    tasks.splice(index, <span class="hljs-number">1</span>);
    res.redirect(<span class="hljs-string">'/list-of-tasks'</span>);
})
<span class="hljs-comment">/** Exporting routes to register in the app to make it available to accept request and return response */</span>
<span class="hljs-built_in">module</span>.exports = router;
</code></pre>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In conclusion, routing in Express.js is a fundamental aspect of building robust and organized web applications, whether you're developing REST APIs or full-stack solutions. By mapping URLs to specific functions or handlers, routing enables us to effectively manage and structure our application code.</p>
<p>We've explored the various components of routing, including URL mapping, dynamic URL handling, middleware integration, and error handling, each contributing to a cleaner and more maintainable codebase. With Express.js's built-in routing capabilities, we can efficiently handle different HTTP methods and modularize our application into manageable routes.</p>
]]></content:encoded></item><item><title><![CDATA[Hello World in Express Js]]></title><description><![CDATA[As per the rituals, the first thing to do to start with any language is print the Hello World, we can also say that as a programmer we love to say hello to the world in different languages.
Before proceeding, let's understand some basics about Expres...]]></description><link>https://blog.jhaabhishek.com/hello-world-in-express-js</link><guid isPermaLink="true">https://blog.jhaabhishek.com/hello-world-in-express-js</guid><category><![CDATA[Node.js]]></category><category><![CDATA[Express.js]]></category><category><![CDATA[Hello World]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Abhishek Jha]]></dc:creator><pubDate>Mon, 29 Jul 2024 14:29:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722263219178/e1b10fde-a3fa-47e6-b5cd-150ea6893698.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As per the rituals, the first thing to do to start with any language is print the <strong>Hello World,</strong> we can also say that as a programmer we love to say hello to the world in different languages.</p>
<p>Before proceeding, let's understand some basics about Express JS. So Express JS is a framework for Node.js. It provides easy ways to define routes, handle requests and responses with middleware, and integrate various features. With Express, you can create REST APIs effortlessly and efficiently manage tasks like user authentication and data handling. Its flexibility and large community support make it a go-to choice for developers building fast and robust web applications.</p>
<p>We need a few things installed in our machine to learn to Express js Node and the code editor of your choice, I recommend <a target="_blank" href="https://code.visualstudio.com/download">VS code</a> as it is free, easy to use, and understandable.</p>
<h2 id="heading-steps">Steps</h2>
<p>Create a folder express-01 and a file with the name main.js you can name it whatever you want and run the below command.</p>
<ol>
<li><p><code>npm install express</code></p>
<p> The above command will install the Express Js into the application folder(express-01).</p>
</li>
<li><p>After installing Express open the main.js file in the code editor and write the below code.</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">/**Importing the express Js */</span>
 <span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);

 <span class="hljs-comment">/** Initializing the express application */</span>
 <span class="hljs-keyword">const</span> app = express();

 <span class="hljs-comment">/** Register the route to accept the get request */</span>
 app.get(<span class="hljs-string">'/'</span>,<span class="hljs-function">(<span class="hljs-params">req,res,next</span>) =&gt;</span> {
     <span class="hljs-comment">/** sending Hello World as a response*/</span>
     res.send(<span class="hljs-string">'Hello World'</span>);
 });

 <span class="hljs-comment">/** Create server and start listing on the port of your choice */</span>
 app.listen(<span class="hljs-number">3000</span>);
</code></pre>
<p> In the above code, we have imported the Express js to use the routing feature and also we have created an instance of an application to serve the get request and return the response.</p>
</li>
</ol>
<p>In the next article, we will learn more about routing including the route verbs request and response and how to use them in the Express application.</p>
]]></content:encoded></item><item><title><![CDATA[Laravel blade]]></title><description><![CDATA[Blade is the templating engine that comes with Laravel to give us the efficient and clean rendering of views which is essential for creating dynamic and visually appealing web applications. Laravel Blade provides a simple yet robust syntax to work wi...]]></description><link>https://blog.jhaabhishek.com/laravel-blade</link><guid isPermaLink="true">https://blog.jhaabhishek.com/laravel-blade</guid><category><![CDATA[Laravel]]></category><category><![CDATA[laravel blade]]></category><category><![CDATA[Web Design]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[PHP]]></category><dc:creator><![CDATA[Abhishek Jha]]></dc:creator><pubDate>Sun, 26 Nov 2023 14:50:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1701009759397/ba046f3a-fe20-4053-8c05-617b6edf0e85.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Blade is the templating engine that comes with Laravel to give us the efficient and clean rendering of views which is essential for creating dynamic and visually appealing web applications. Laravel Blade provides a simple yet robust syntax to work with views and helps developers create layouts, partials, and components with ease. It's friendly for people just starting out in web development and also has some secret tricks that more experienced developers can use to make websites work even better. Blade basically makes web building more like fun arts and crafts than hard computer stuff. Blade template files use the <code>.blade.php</code> file extension and are typically stored in the <code>resources/views</code> directory of Laravel.</p>
<h3 id="heading-why-laravel-blade"><strong>Why Laravel Blade?</strong></h3>
<ol>
<li><p><strong>Clean and Expressive Syntax</strong></p>
<p> Blade's syntax is like a breath of fresh air in the web development world. It's a mix of regular HTML and simple codes that make it super-readable and easy to understand. Unlike raw PHP, Blade keeps things tidy, making it a delight for developers to work with.</p>
</li>
<li><p><strong>Template Inheritance for Consistency</strong></p>
<p> One big reason we love Blade is its template inheritance feature. This means you can create a layout for your website once and use it everywhere without rewriting the same code. It's like having a master plan for your website's design that you can reuse effortlessly.</p>
</li>
<li><p><strong>Encourages Best Practices</strong></p>
<p> Blade encourages separating different parts of your code, like keeping logic in one place and design in another. This separation of concerns helps in better organization and makes your code easier to understand and maintain.</p>
</li>
<li><p><strong>Directives and Control Structures</strong></p>
<p> Laravel Blade offers powerful directives and control structures (such as <strong>loops</strong>, <strong>conditional statements</strong>, and <strong>includes</strong>) to manipulate data and control the flow of the application logic directly within the views.</p>
</li>
<li><p><strong>Performance and Optimization</strong></p>
<p> Blade doesn't just make things pretty, it's also efficient. Laravel allows caching views created with Blade, which means your website can load faster by saving pre-rendered views, especially useful for frequently visited pages.</p>
</li>
<li><p><strong>Community and Support</strong></p>
<p> Laravel, with Blade as its shining star, has a vibrant community. This means plenty of resources, tutorials, and support available online. If you ever get stuck or want to learn more, there's always a helping hand or a tutorial just a click away.</p>
</li>
</ol>
<h3 id="heading-basics-of-laravel-blade">Basics of Laravel Blade</h3>
<ol>
<li><p><strong>Introduction to Blade Syntax</strong></p>
<ol>
<li><p><strong>Echo Variables</strong> <code>{{$name}}</code> shows the content of a variable, like displaying a person's name stored in $name, and it's automatically sent through PHP's <code>htmlspecialchars</code> function to prevent XSS (<strong>Cross-site scripting</strong>) attacks.</p>
<p> You are not limited to just printing the values stored in the variable you can print the result of functions as well as you can you can put any PHP code you wish inside of a Blade echo statement</p>
<pre><code class="lang-php"> &lt;!-- Displaying Variables --&gt;
 {{ $name }}

 &lt;!-- Displaying resut of a funtion --&gt;
 The current UNIX timestamp is {{ time() }}.
</code></pre>
</li>
<li><p><strong>IF conditions in Blade</strong>: It checks if someone is logged in ($isLoggedIn). If true, it says a welcome message with the name; otherwise, it asks to log in.</p>
<pre><code class="lang-php"> @<span class="hljs-keyword">if</span>($isLoggedIn)
     &lt;p&gt;Welcome, {{ $username }}!&lt;/p&gt;
 @<span class="hljs-keyword">endif</span>

 &lt;!-- Using @<span class="hljs-keyword">if</span>/@<span class="hljs-keyword">else</span> --&gt;

 @<span class="hljs-keyword">if</span>($isAdmin)
     &lt;p&gt;Welcome, Admin!&lt;/p&gt;
 @<span class="hljs-keyword">else</span>
     &lt;p&gt;Welcome, User!&lt;/p&gt;
 @<span class="hljs-keyword">endif</span>

 &lt;!-- Using @<span class="hljs-keyword">if</span>/@<span class="hljs-keyword">elseif</span>/@<span class="hljs-keyword">else</span> --&gt;

 @<span class="hljs-keyword">if</span>($userRole === <span class="hljs-string">'admin'</span>)
     &lt;p&gt;Welcome, Admin!&lt;/p&gt;
 @<span class="hljs-keyword">elseif</span>($userRole === <span class="hljs-string">'moderator'</span>)
     &lt;p&gt;Welcome, Moderator!&lt;/p&gt;
 @<span class="hljs-keyword">else</span>
     &lt;p&gt;Welcome, User!&lt;/p&gt;
 @<span class="hljs-keyword">endif</span>
</code></pre>
</li>
<li><p><strong>Loops in Blade:</strong></p>
<p> Laravel Blade provides several directives for looping through arrays or collections and offers loop-related variables to access information about the current iteration. Let's explore each loop directive and its associated loop variables.</p>
<ol>
<li><p><code>@foreach</code> <strong>Loop</strong></p>
<ul>
<li><p>Initiates a loop through the <code>$items</code> array or collection. <code>$items</code> represent the data source being iterated, and <code>$item</code> is the loop variable that holds each item during iterations.</p>
</li>
<li><p><code>&lt;p&gt;{{ $item }}&lt;/p&gt;</code>: Within the loop, <code>{{ $item }}</code> displays each item in the <code>$items</code> array within <code>&lt;p&gt;</code> tags.</p>
<pre><code class="lang-php">  @<span class="hljs-keyword">foreach</span>($items <span class="hljs-keyword">as</span> $item)
      &lt;p&gt;{{ $item }}&lt;/p&gt;
  @<span class="hljs-keyword">endforeach</span>
</code></pre>
</li>
</ul>
</li>
<li><p><code>@forelse</code> <strong>Loop:</strong></p>
<p> The <code>@forelse</code> directive in Laravel Blade is specifically designed to handle looping through data while also managing empty states more elegantly compared to traditional loops.</p>
<p> <code>@empty</code>: This section is executed if the <code>$user</code> array is empty. It shows a message, like "No users"</p>
<pre><code class="lang-php"> @forelse ($users <span class="hljs-keyword">as</span> $user)
     &lt;li&gt;{{ $user-&gt;name }}&lt;/li&gt;
 @<span class="hljs-keyword">empty</span>
     &lt;p&gt;No users&lt;/p&gt;
 @endforelse
</code></pre>
</li>
<li><p><code>@for</code> <strong>Loop:</strong></p>
<ul>
<li><p><code>@for($i = 0; $i &lt; count($numbers); $i++)</code>: Sets up a traditional <code>for</code> loop. Here, <code>$i</code> serves as the loop counter starting from 0, iterating until the condition is met (<code>$i &lt; count($numbers)</code>).</p>
</li>
<li><p><code>&lt;p&gt;{{ $numbers[$i] }}&lt;/p&gt;</code>: Displays each element of the <code>$numbers</code> array using the loop counter <code>$i</code> to access individual elements.</p>
<pre><code class="lang-php">   @<span class="hljs-keyword">for</span>($i = <span class="hljs-number">0</span>; $i &lt; count($numbers); $i++)
       &lt;p&gt;{{ $numbers[$i] }}&lt;/p&gt;
   @<span class="hljs-keyword">endfor</span>
</code></pre>
</li>
</ul>
</li>
<li><p><code>@while</code> <strong>Loop</strong></p>
<pre><code class="lang-php"> @php
     $counter = <span class="hljs-number">0</span>;
 @endphp

 @<span class="hljs-keyword">while</span>($counter &lt; <span class="hljs-number">5</span>)
     &lt;p&gt;{{ $counter }}&lt;/p&gt;
     @php
         $counter++;
     @endphp
 @<span class="hljs-keyword">endwhile</span>
</code></pre>
</li>
<li><p><strong>Loop Variables in Blade:</strong></p>
<ol>
<li><p><strong>$loop-&gt;index</strong> The index of the current loop iteration (starts at 0).</p>
</li>
<li><p><strong>$loop-&gt;iteration</strong> The current loop iteration (starts at 1).</p>
</li>
<li><p><strong>$loop-&gt;remaining</strong> The iterations remaining in the loop.</p>
</li>
<li><p><strong>$loop-&gt;count</strong> The total number of items in the array being iterated.</p>
</li>
<li><p><strong>$loop-&gt;first</strong> Whether this is the first iteration through the loop.</p>
</li>
<li><p><strong>$loop-&gt;last</strong> Whether this is the last iteration through the loop.</p>
</li>
<li><p><strong>$loop-&gt;even</strong> Whether this is an even iteration through the loop.</p>
</li>
<li><p><strong>$loop-&gt;odd</strong> Whether this is an odd iteration through the loop.</p>
</li>
<li><p><strong>$loop-&gt;depth</strong> The nesting level of the current loop.</p>
</li>
<li><p><strong>$loop-&gt;parent</strong> When in a nested loop, the parent's loop variable.</p>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
</ol>
<pre><code class="lang-php">            $countries = [<span class="hljs-string">'USA'</span>, <span class="hljs-string">'Canada'</span>, <span class="hljs-string">'UK'</span>, <span class="hljs-string">'Australia'</span>];

            @<span class="hljs-keyword">foreach</span>($countries <span class="hljs-keyword">as</span> $country)
                &lt;p&gt;
                    Index: {{ $loop-&gt;index }} |
                    Iteration: {{ $loop-&gt;iteration }} |
                    First: {{ $loop-&gt;first ? <span class="hljs-string">'Yes'</span> : <span class="hljs-string">'No'</span> }} |
                    Last: {{ $loop-&gt;last ? <span class="hljs-string">'Yes'</span> : <span class="hljs-string">'No'</span> }} |
                    Count: {{ $loop-&gt;count }} |
                    Total Items: {{ $loop-&gt;total }} |
                    Odd/Even: {{ $loop-&gt;odd ? <span class="hljs-string">'Odd'</span> : <span class="hljs-string">'Even'</span> }} |
                    {{ $country }}
                &lt;/p&gt;
            @<span class="hljs-keyword">endforeach</span>
</code></pre>
<ol>
<li><p><code>@switch</code> <code>@case</code> and <code>@default</code></p>
<p> The <code>@switch</code>, <code>@case</code>, and <code>@default</code> directives in Laravel Blade provide a structured way to handle complex conditional logic. They function similarly to the switch-case-default construct in PHP.</p>
<pre><code class="lang-php"> @<span class="hljs-keyword">switch</span>($role)
     @<span class="hljs-keyword">case</span>(<span class="hljs-string">'admin'</span>)
         &lt;p&gt;Welcome, Admin!&lt;/p&gt;
         @<span class="hljs-keyword">break</span>

     @<span class="hljs-keyword">case</span>(<span class="hljs-string">'user'</span>)
         &lt;p&gt;Welcome, User!&lt;/p&gt;
         @<span class="hljs-keyword">break</span>

     @<span class="hljs-keyword">default</span>
         &lt;p&gt;Unknown Role&lt;/p&gt;
 @<span class="hljs-keyword">endswitch</span>
</code></pre>
</li>
</ol>
<h3 id="heading-laravel-blade-directives">Laravel Blade Directives</h3>
<p>Blade directives are special syntax or instructions used in Laravel Blade templates to streamline and enhance the readability and functionality of your views. Here's an overview of some commonly used Blade directives</p>
<ol>
<li><p><code>@include</code></p>
<ol>
<li><p>The <code>@include</code> directive in Laravel Blade is used to include and render other Blade views or partials within a Blade template. It enables the reusability of code by allowing you to insert the contents of another Blade file into the current file.</p>
<p> This includes the content of the <code>partials/header.blade.php</code> file in the current Blade template at the location where the <code>@include</code> directive is placed.</p>
<pre><code class="lang-php"> @<span class="hljs-keyword">include</span>(<span class="hljs-string">'partials.header'</span>)
</code></pre>
</li>
<li><p>With Variables</p>
<p> In this case, the <code>partials/product.blade.php</code> file is included, and it's passed a variable <code>$product</code> to use within that included file.</p>
<pre><code class="lang-php"> $product = App\Models\Product::all();

 @<span class="hljs-keyword">include</span>(<span class="hljs-string">'partials.product'</span>, [<span class="hljs-string">'product'</span> =&gt; $product])

 &lt;!-- Second Exampe --&gt;

 @<span class="hljs-keyword">include</span>(<span class="hljs-string">'partials.product'</span>, compact(<span class="hljs-string">'product'</span>))
</code></pre>
</li>
</ol>
</li>
<li><p><code>@includeWhen</code></p>
<p> The <code>@includeWhen</code> directive in Laravel Blade is a conditional way to include a Blade view or partial based on a given condition. It's similar to the <code>@include</code> directive but includes the specified view only when the condition provided evaluates to <code>true</code>.</p>
<p> Difference between <code>@include</code> and <code>@includeWhen</code>:</p>
<p> <code>@include</code> It unconditionally includes the specified Blade view or partial in the current template regardless of any condition.</p>
<p> It's used for unconditional inclusion.</p>
<p> <code>@includeWhen</code>: It includes the specified view based on a condition. If the condition is true, the view is included; otherwise, it's skipped. It's suitable for conditional inclusion.</p>
<pre><code class="lang-php"> @includeWhen($condition, <span class="hljs-string">'partials.header'</span>)
  &lt;!-- With Variable --&gt;
 @includeWhen($user-&gt;isAdmin(), <span class="hljs-string">'partials.admin-menu'</span>, [<span class="hljs-string">'user'</span> =&gt; $user])
</code></pre>
</li>
<li><p><code>@auth</code> and <code>@guest</code></p>
<p> The <code>@auth</code> and <code>@guest</code> directives in Laravel Blade provide convenient ways to conditionally display content based on whether a user is authenticated (<code>@auth</code>) or is a guest (not authenticated, <code>@guest</code>). These directives simplify the rendering of specific content based on the user's authentication status.</p>
<pre><code class="lang-php"> @auth
     &lt;!-- Display content <span class="hljs-keyword">if</span> user is authenticated --&gt;
 @endauth

 @guest
     &lt;!-- Display content <span class="hljs-keyword">if</span> user is a guest (not authenticated) --&gt;
 @endguest
</code></pre>
</li>
<li><p><code>@isset</code> and <code>@empty</code></p>
<pre><code class="lang-php"> @<span class="hljs-keyword">isset</span>($variable)
     &lt;!-- Display content <span class="hljs-keyword">if</span> $variable is set <span class="hljs-keyword">and</span> not <span class="hljs-literal">null</span> --&gt;
 @endisset

 @<span class="hljs-keyword">empty</span>($items)
     &lt;!-- Display content <span class="hljs-keyword">if</span> $items is <span class="hljs-keyword">empty</span> --&gt;
 @endempty
</code></pre>
</li>
<li><p><code>@verbatim</code><br /> The <code>@verbatim</code> directive in Laravel Blade is used to render content as raw, plain text, ignoring Blade's default templating behavior. This directive allows you to display code snippets, text blocks, or any content without being processed by Blade's syntax parser.</p>
<p> Avoid excessive use of <code>@verbatim</code> as it bypasses Blade's powerful templating capabilities. It's typically used sparingly in specific scenarios where you need to preserve the original content without modification by Blade.</p>
<p> In this case, the content inside <code>@verbatim</code> will be displayed exactly as written, without Blade interpreting the <code>{{ }}</code> or <code>@if</code> conditions. The entire block will be rendered as plain text.</p>
<pre><code class="lang-php"> @verbatim
     &lt;p&gt;{{ $name }}&lt;/p&gt;
     @<span class="hljs-keyword">if</span>($status == <span class="hljs-string">'active'</span>)
         &lt;span&gt;Status: Active&lt;/span&gt;
     @<span class="hljs-keyword">else</span>
         &lt;span&gt;Status: Inactive&lt;/span&gt;
     @<span class="hljs-keyword">endif</span>
 @endverbatim
</code></pre>
</li>
<li><p><code>@csrf</code></p>
<p> <code>@csrf</code> in Laravel Blade is a directive used for security purposes, specifically to prevent Cross-Site Request Forgery (CSRF) attacks. CSRF attacks occur when a malicious website tricks a user's browser into performing actions on another site without the user's knowledge, using their authenticated session.</p>
<p> By using <code>@csrf</code> in your forms, Laravel ensures that your application is better protected against CSRF attacks, safeguarding the actions performed by your users.</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">"/submit"</span>&gt;</span>
     @csrf
     <span class="hljs-comment">&lt;!-- Other form fields --&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
</li>
</ol>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>Laravel Blade is a super easy way to make awesome websites and web applications. It's like using magic blocks to build your webpage. With simple commands, you can create cool designs, show different things to different people, and keep your site safe. Plus, it helps your webpage load faster, and there are lots of online friends to help you learn more. Start using Blade and make something amazing!</p>
]]></content:encoded></item><item><title><![CDATA[Why Sanctum is the best fit for SPA authentication.]]></title><description><![CDATA[Authentication and authorization are crucial aspects of software development, today we will see how Sanctum is the best suit for SPA(Single Page Application) and mobile API authentication and authorization. Laravel has two major packages that are Lar...]]></description><link>https://blog.jhaabhishek.com/why-sanctum-is-the-best-fit-for-spa-authentication</link><guid isPermaLink="true">https://blog.jhaabhishek.com/why-sanctum-is-the-best-fit-for-spa-authentication</guid><category><![CDATA[Laravel]]></category><category><![CDATA[Laravel Sanctum]]></category><category><![CDATA[Single Page Application]]></category><category><![CDATA[APIs]]></category><category><![CDATA[Laravel-API]]></category><dc:creator><![CDATA[Abhishek Jha]]></dc:creator><pubDate>Tue, 17 Oct 2023 14:56:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1697471783979/96b57d38-a9a5-4f3e-beaa-103431fbb06b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Authentication and authorization are crucial aspects of software development, today we will see how Sanctum is the best suit for SPA(Single Page Application) and mobile API authentication and authorization. Laravel has two major packages that are <strong>Laravel Passport</strong> and <strong>Laravel Sanctum</strong> depending on the use case you can choose one of them, but when it's about SPA and you don't have any need for the <strong>OAuth2</strong> going with Sanctum will be the best, we will discuss why and how?</p>
<p><strong>Laravel Sanctum primarily solves two problems</strong></p>
<ol>
<li><p><strong>API Tokens</strong></p>
<p> Sanctum provides API tokens without the complication of <strong>OAuth</strong> by providing personal access tokens inspired by GitHub and other applications that use personal authentication tokens for authentication and authorization. Sanctum achieves this by storing the access token in the database and authorizing incoming HTTP requests via the Authorization header.</p>
</li>
<li><p><strong>SPA Authentication</strong></p>
<p> Sanctum offers an easy way to authenticate Single Page Applications (SPA), communicating with the APIs developed using Laravel. You can use Sanctum whether you are using a separate application for frontend developed in Vue or React, or you are using Laravel with Vue or React with Laravel in one project.</p>
<p> Sanctum uses the default cookie-based service for authentication that comes in the default authentication for the web in Laravel, That's why you don't need any token-based authentication for your Single Page Application.</p>
<p> The benefits of using this is you will get <strong>CSRF Protection</strong> and <strong>session authentication</strong>, and also gives <strong>protection against the leakage of authentication credentials vis XSS(Cross-Site Scripting.)</strong>.</p>
<p> It is not compulsory to use cookie-based authentication, you can use token-based authentication also. Sanctum will only use cookie-based authentication if it's coming from your SPA otherwise it will look for the <strong>Authorization</strong> header for a valid API token.</p>
<p> As of now, we have a detailed introduction to Sanctum and the working mechanism, so now we will explore how to implement it in our application.</p>
</li>
<li><p><strong>Sanctum Implementation</strong></p>
<ol>
<li><p><strong>Installation</strong></p>
<pre><code class="lang-powershell"> composer require laravel/sanctum
</code></pre>
</li>
<li><p><strong>Publish Configuration</strong></p>
<pre><code class="lang-powershell"> php artisan vendor:publish -<span class="hljs-literal">-provider</span>=<span class="hljs-string">"Laravel\Sanctum\SanctumServiceProvider"</span>
</code></pre>
</li>
<li><p><strong>Run migration</strong></p>
<p> To create a table in your database to store authentication tokens</p>
<pre><code class="lang-powershell"> php artisan migrate
</code></pre>
</li>
<li><p><strong>Adding Middleware</strong></p>
<p> If you want to use the sanctum for your Single Page Application (SPA) you should add the below middleware to your <code>api</code> middleware group or else you can ignore this step. The <code>EnsureFrontendRequestsAreStateful</code> middleware to the <code>API</code> middleware group. This middleware is provided by Sanctum and is crucial for ensuring that authentication tokens are properly handled between the SPA and the backend. It maintains the statefulness of the authentication session, allowing users to remain logged in while navigating your SPA.</p>
<pre><code class="lang-php"> <span class="hljs-string">'api'</span> =&gt; [
     \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
     \Illuminate\Routing\Middleware\ThrottleRequests::class.<span class="hljs-string">':api'</span>,
     \Illuminate\Routing\Middleware\SubstituteBindings::class,
 ],
</code></pre>
</li>
<li><p><strong>Configure CORS (Cross-Origin Resource Sharing)</strong></p>
<p> CORS is a security feature implemented in web browsers to control which web pages can access resources on a given domain. In this step, you are configuring your Laravel application to allow requests from your SPA's domain. By specifying your SPA's URL in the <code>allowed_origins</code> array, you are permitting it to make requests to your Laravel application. This step ensures that your SPA can communicate with your API without encountering CORS-related issues.</p>
<p> Add the below code in <code>config/cors.php</code> add your SPA URL in <code>paths</code> array.</p>
<pre><code class="lang-php"> <span class="hljs-string">'paths'</span> =&gt; [<span class="hljs-string">'api/*'</span>, <span class="hljs-string">'sanctum/csrf-cookie'</span>, <span class="hljs-string">'login'</span>, <span class="hljs-string">'logout'</span>],
 <span class="hljs-string">'allowed_methods'</span> =&gt; [<span class="hljs-string">'*'</span>],
 <span class="hljs-string">'allowed_origins'</span> =&gt; [env(<span class="hljs-string">'SPA_URL'</span>)], <span class="hljs-comment">// your SPA URL</span>
 <span class="hljs-string">'allowed_origins_patterns'</span> =&gt; [],
 <span class="hljs-string">'allowed_headers'</span> =&gt; [<span class="hljs-string">'*'</span>],
 <span class="hljs-string">'exposed_headers'</span> =&gt; [],
 <span class="hljs-string">'max_age'</span> =&gt; <span class="hljs-number">0</span>,
 <span class="hljs-string">'supports_credentials'</span> =&gt; <span class="hljs-literal">true</span>,
</code></pre>
</li>
<li><p><strong>Create API Routes</strong></p>
<p> Create your API routes in <code>routes/api.php</code> file.</p>
<pre><code class="lang-php"> <span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">API</span>\<span class="hljs-title">AuthController</span>;
 <span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>\<span class="hljs-title">API</span>\<span class="hljs-title">YourController</span>;

 Route::prefix(<span class="hljs-string">'auth'</span>)-&gt;group(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
     Route::post(<span class="hljs-string">'/login'</span>, [AuthController::class, <span class="hljs-string">'login'</span>]);
     Route::post(<span class="hljs-string">'/register'</span>, [AuthController::class, <span class="hljs-string">'register'</span>]);
     Route::middleware(<span class="hljs-string">'auth:sanctum'</span>)-&gt;post(<span class="hljs-string">'/logout'</span>, [AuthController::class, <span class="hljs-string">'logout'</span>]);
 });

 Route::middleware(<span class="hljs-string">'auth:sanctum'</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">'/user'</span>, [AuthController::class, <span class="hljs-string">'user'</span>]);
 });
</code></pre>
</li>
<li><p><strong>Implement SPA Authentication</strong></p>
<p> In your SPA (Single Page Application), you need to implement the frontend logic for user authentication. Here, Axios, a popular HTTP client for JavaScript, is configured to handle requests. Axios is used to send HTTP requests to your Laravel API. The <code>withCredentials</code> property is set to <code>true</code> to include credentials (such as cookies) with requests. The <code>login</code> and <code>logout</code> functions demonstrate how to perform user login and logout operations. These functions handle sending requests to the appropriate API endpoints (<code>/api/auth/login</code> and <code>/api/auth/logout</code>) and manage the user's authentication status in your SPA.</p>
<pre><code class="lang-javascript">
 axios.defaults.withCredentials = <span class="hljs-literal">true</span>;

 <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">login</span>(<span class="hljs-params">email, password</span>) </span>{
     <span class="hljs-keyword">try</span> {
         <span class="hljs-keyword">await</span> axios.get(<span class="hljs-string">'/sanctum/csrf-cookie'</span>);
         <span class="hljs-keyword">await</span> axios.post(<span class="hljs-string">'/api/auth/login'</span>, {
             <span class="hljs-attr">email</span>: email,
             <span class="hljs-attr">password</span>: password
         });

     } <span class="hljs-keyword">catch</span> (error) {

     }
 }

 <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logout</span>(<span class="hljs-params"></span>) </span>{
     <span class="hljs-keyword">try</span> {
         <span class="hljs-keyword">await</span> axios.post(<span class="hljs-string">'/api/auth/logout'</span>);

     } <span class="hljs-keyword">catch</span> (error) {

     }
 }
</code></pre>
</li>
</ol>
</li>
</ol>
<p><strong>Conclusion</strong><br />Laravel Sanctum emerges as the top choice for Single Page Applications (SPAs) seeking secure and streamlined authentication solutions. Unlike its counterpart Laravel Passport, Sanctum simplifies the complex process of API token management and offers effortless SPA authentication. By storing access tokens securely and employing cookie-based authentication, Sanctum ensures robust security measures, including CSRF protection and defense against cross-site scripting attacks. Its seamless integration capabilities make it a preferred option for developers, allowing them to focus on building user-friendly, secure SPAs without the complexities of intricate authentication systems. Sanctum’s simplicity, enhanced security, and seamless integration make it the go-to solution for modern SPAs in the ever-evolving landscape of web development.</p>
]]></content:encoded></item><item><title><![CDATA[How to make code clean and consistent.]]></title><description><![CDATA[In this blog, we will discuss the default CLI app that comes with Laravel 9 to make your code clean and consistent. If you're a developer immersed in modern PHP, you know how essential it is to maintain a clean and consistent code style. Over the yea...]]></description><link>https://blog.jhaabhishek.com/how-to-make-code-clean-and-consistent</link><guid isPermaLink="true">https://blog.jhaabhishek.com/how-to-make-code-clean-and-consistent</guid><category><![CDATA[Laravel]]></category><category><![CDATA[PHP]]></category><category><![CDATA[coding]]></category><category><![CDATA[Developer]]></category><category><![CDATA[codingstyle]]></category><dc:creator><![CDATA[Abhishek Jha]]></dc:creator><pubDate>Sat, 30 Sep 2023 10:55:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1696070785490/0bfba9a1-b01c-4264-aea5-b00924fc447a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this blog, we will discuss the default CLI app that comes with Laravel 9 to make your code clean and consistent. If you're a developer immersed in modern PHP, you know how essential it is to maintain a clean and consistent code style. Over the years, PHP has evolved, and with initiatives like PHP-FIG and the release of PSRs, the community has emphasized code quality, consistency, and adherence to standards.</p>
<p>As we all know Laravel has huge open-source packages to help in every situation, we have a package to help us in this situation also and the package is Laravel <strong>Pint.</strong> <strong>Laravel Pint</strong> is a zero-dependency PHP code style fixer for minimalists - built on top of PHP-CS-Fixer. For Laravel 9 and other latest versions, this package is included in the default installation of Laravel, for older versions you can install this by using the composer.</p>
<p>Automating code style checks and fixes based on a preset, making it effortless to ensure your code conforms to best practices. Let's dive into the world of Laravel Pint and see how it simplifies code styling by using some simple steps.</p>
<h2 id="heading-installation"><strong>Installation</strong></h2>
<p>Install the package for the Larvel 8 and other older versions.</p>
<pre><code class="lang-php">composer <span class="hljs-keyword">require</span> laravel/pint --dev
</code></pre>
<h3 id="heading-using-laravel-pint"><strong>Using Laravel Pint</strong></h3>
<p>As we have discussed earlier Laravel pint can be used without doing any configuration you can fix the code style issue of your application by just running the below command.</p>
<pre><code class="lang-php">./vendor/bin/pint
</code></pre>
<p>No need to worry about configurations, presets or any other setup, Changes will be done according to the PSR-12 styling, and any issue will be automatically fixed. It will work like a magical command to keep your code clean and consistent!</p>
<p><strong>Use case scenarios</strong></p>
<ol>
<li><p><strong>Run the command to check and fix all the files of your application</strong></p>
<pre><code class="lang-php"> ./vendor/bin/pint
</code></pre>
</li>
<li><p><strong>Run on a specific Folder</strong></p>
<pre><code class="lang-php"> ./vendor/bin/pint app/Models
</code></pre>
</li>
<li><p><strong>Run on a specific File</strong></p>
<pre><code class="lang-php"> ./vendor/bin/pint app/Models/User.php
</code></pre>
</li>
<li><p><strong>View the list of updated files by Pint</strong></p>
<pre><code class="lang-php"> ./vendor/bin/pint -v
</code></pre>
</li>
<li><p><strong>Check the files without changing them</strong></p>
<pre><code class="lang-php"> ./vendor/bin/pint --test
</code></pre>
</li>
<li><p><strong>Run the test only on the files with uncommitted changes</strong></p>
<pre><code class="lang-php"> ./vendor/bin/pint --dirty
</code></pre>
</li>
</ol>
<h3 id="heading-configuration"><strong>Configuration</strong></h3>
<p>By default, we do not need any configuration to run the pint but we can change the configuration according to your need. You can change the preset rules and inspected folders by creating the <code>pint.json</code> file in your root directory.</p>
<ol>
<li><p><strong>Preset</strong></p>
<p> Preset defines a set of rules to fix the code style issue in the file.</p>
<p> By default, the preset value is Laravel so it will follow the opinionated coding style of Laravel. You can change the value as per your needs in <code>pint.json</code> supported presets are <code>laravel</code>, <code>per</code>, <code>psr12</code>, and <code>symfony</code>.</p>
<pre><code class="lang-json"> {
     <span class="hljs-attr">"preset"</span>: <span class="hljs-string">"psr12"</span>
 }
</code></pre>
</li>
<li><p><strong>Rules</strong></p>
<p> As presets are already a set of predefined rules, probably you will not change the configuration files, however, there are options available to change the rules.</p>
<p> As Pint is built on PHP-CS-Fixer you can use any of it's <a target="_blank" href="https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/master/doc/rules/index.rst">rules available for styling.</a></p>
<pre><code class="lang-json"> {
     <span class="hljs-attr">"preset"</span>: <span class="hljs-string">"psr12"</span>,
     <span class="hljs-attr">"rules"</span>: {
         <span class="hljs-attr">"simplified_null_return"</span>: <span class="hljs-literal">true</span>,
         <span class="hljs-attr">"braces"</span>: <span class="hljs-literal">false</span>,
         <span class="hljs-attr">"new_with_braces"</span>: {
             <span class="hljs-attr">"anonymous_class"</span>: <span class="hljs-literal">false</span>,
             <span class="hljs-attr">"named_class"</span>: <span class="hljs-literal">false</span>
         }
 }
</code></pre>
</li>
<li><p><strong>Excluding Folders/Files</strong></p>
<p> Pint will check all the <code>.php</code> files except the <code>vendor</code> directory, you can exclude the files and folders you want</p>
<pre><code class="lang-json"> {
     <span class="hljs-attr">"exclude"</span>: [
         <span class="hljs-string">"my-specific/folder"</span>
     ],
     <span class="hljs-attr">"notName"</span>: [
         <span class="hljs-string">"*-my-file.php"</span>
     ],
     <span class="hljs-attr">"notPath"</span>: [
         <span class="hljs-string">"path/to/excluded-file.php"</span>
     ]
 }
</code></pre>
</li>
</ol>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>Laravel Pint is a must install tool for any PHP developer working on projects, packages, or anything else that involves writing PHP code. With its simplicity, zero-dependency approach, and flexibility in configuration, it's a powerful addition to your toolkit. Say goodbye to messy PHP arrays and complex rule configurations. Laravel Pint streamlines the process of maintaining a clean and consistent code style. Start using it in your projects today and experience the magic of effortless code styling. 🚀</p>
]]></content:encoded></item><item><title><![CDATA[Future Proof Your Code with Design Patterns and Principles]]></title><description><![CDATA[Introduction :
In the ever-evolving world of software development, one key aspect that separates exceptional software from the mediocre is the thoughtful application of design patterns and principles. These invaluable tools provide a systematic appro...]]></description><link>https://blog.jhaabhishek.com/future-proof-your-code-with-design-patterns-and-principles</link><guid isPermaLink="true">https://blog.jhaabhishek.com/future-proof-your-code-with-design-patterns-and-principles</guid><category><![CDATA[design principles]]></category><category><![CDATA[OOP Design Principles]]></category><category><![CDATA[SOLID principles]]></category><category><![CDATA[Laravel]]></category><category><![CDATA[PHP]]></category><dc:creator><![CDATA[Abhishek Jha]]></dc:creator><pubDate>Fri, 21 Jul 2023 03:58:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1689874500984/581500a4-0c72-4dab-9113-270f01bb12e3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Introduction :</strong></p>
<p>In the ever-evolving world of software development, one key aspect that separates exceptional software from the mediocre is the thoughtful application of design patterns and principles. These invaluable tools provide a systematic approach to problem-solving, enabling developers to create well-structured, maintainable, and extensible codebases. In this blog, we will explore why it is crucial to embrace design patterns and principles in software development and how they can significantly impact the quality and efficiency of your projects.</p>
<ol>
<li><p><strong>Reusability and Maintainability:</strong></p>
<p> Design patterns offer a proven set of solutions to commonly occurring problems in software development. By utilizing these patterns, developers can tap into a wealth of knowledge and experience accumulated by the community. Design patterns promote code reuse, allowing you to leverage existing solutions rather than reinvent the wheel. This, in turn, reduces development time, enhances productivity, and facilitates the maintenance of codebases over time. By adhering to well-established patterns, future developers can easily understand and modify the code, leading to increased project longevity.</p>
</li>
<li><p><strong>Scalability and Flexibility:</strong></p>
<p> As software applications grow in complexity, scalability becomes a critical consideration. Design patterns enable developers to build scalable software architectures that can adapt and evolve with changing requirements. Patterns like the Observer pattern facilitate loose coupling between components, allowing for easy integration of new features without impacting existing code. The use of design patterns ensures that your software can handle increased user loads, evolving business needs, and technological advancements without requiring a complete rewrite.</p>
</li>
<li><p><strong>Enhancing Collaboration:</strong></p>
<p> Software development is rarely a solitary endeavor. Teams of developers collaborate to build innovative applications. Design patterns and principles provide a common language and set of guidelines that promote effective collaboration. When team members follow established patterns, it becomes easier to understand and reason about each other's code. Design patterns establish a shared vocabulary and a consistent approach to problem-solving, enhancing communication and teamwork. By adhering to principles such as the Single Responsibility Principle (SRP) and the Open-Closed Principle (OCP), codebases become more modular and comprehensible, enabling seamless collaboration among team members.</p>
</li>
<li><p><strong>Testability and Quality Assurance:</strong></p>
<p> Testing and quality assurance are integral parts of the software development lifecycle. Applying design patterns and principles greatly improves testability. Patterns such as the Dependency Injection pattern enable the creation of modular, testable code by promoting loose coupling and separation of concerns. This allows for the isolation of components during unit testing, making it easier to detect and fix issues. By adhering to principles like the Interface Segregation Principle (ISP) and the Dependency Inversion Principle (DIP), software becomes more modular and easier to test. The result is increased code coverage, improved software quality, and reduced maintenance costs.</p>
</li>
<li><p><strong>Future-Proofing and Knowledge Transfer:</strong></p>
<p> Technology is constantly evolving, and software projects have a long lifespan. Design patterns and principles provide a future-proof foundation for your applications. By adopting widely recognized patterns, you ensure that your codebase remains relevant and adaptable to new technologies and paradigms. Furthermore, design patterns and principles facilitate knowledge transfer among developers. When new team members join a project, having a well-documented and pattern-based codebase helps them quickly understand the system's architecture and design decisions, ensuring continuity and reducing the learning curve.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Boost Your Laravel CRUD Efficiency]]></title><description><![CDATA[Certainly! To make Laravel CRUD faster and save time, consider the following tips and techniques:

In Laravel, many patterns and structures are followed, making it easier for developers to create models, assign tables, and write controllers. By lever...]]></description><link>https://blog.jhaabhishek.com/boost-your-laravel-crud-efficiency</link><guid isPermaLink="true">https://blog.jhaabhishek.com/boost-your-laravel-crud-efficiency</guid><category><![CDATA[Laravel]]></category><category><![CDATA[CRUD Operations]]></category><category><![CDATA[crud]]></category><category><![CDATA[mvc]]></category><category><![CDATA[laravelframework]]></category><dc:creator><![CDATA[Abhishek Jha]]></dc:creator><pubDate>Sat, 08 Jul 2023 12:12:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1688818149029/c880734c-3dfd-4888-af13-5c55ca59edc6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Certainly! To make Laravel CRUD faster and save time, consider the following tips and techniques:</p>
<ol>
<li><p>In Laravel, many patterns and structures are followed, making it easier for developers to create models, assign tables, and write controllers. By leveraging Laravel's conventions, we can save time and effort. Let's explore some shortcuts and methods to speed up development without worrying about naming conventions and patterns.</p>
</li>
<li><p>In Laravel, the model plays a central role in CRUD operations, with other files associated with it. To create a model class efficiently, use the artisan command, ensuring you follow the naming convention. Laravel will generate the remaining associated files automatically using additional parameters provided with the command. This approach streamlines the process and eliminates the need to create related files manually.</p>
<p> <code>php artisan make:model ModelName</code></p>
<hr />
<ol>
<li><p>List of options available with make model command</p>
<ol>
<li><p><code>--migration</code> or <code>-m</code>: This option creates a new migration file along with the model. It generates a database migration file with the appropriate schema for creating the corresponding table in the database. This is useful when you want to quickly create the model and its associated migration at the same time.</p>
</li>
<li><p><code>--controller</code> or <code>-c</code>: This option generates a new controller along with the model. It creates a controller class that can be used to handle the CRUD operations related to the model. The controller is generated with the appropriate naming convention and basic methods such as index, create, store, show, edit, update, and destroy.</p>
</li>
<li><p><code>--factory</code> or <code>-f</code>: This option generates a factory class for the model. A factory class allows you to define the blueprint for creating fake data for testing or seeding your database. It provides a convenient way to generate sample records that adhere to your model's structure.</p>
</li>
<li><p><code>--resource</code> or <code>-r</code>: This option generates a resource class for the model. A resource class helps in transforming your model data into a JSON representation. It is useful when building APIs or working with data that needs to be returned in a specific format.</p>
</li>
<li><p><code>--seed</code> or <code>-s</code> This option generated a seeder file for the model.</p>
<p> A seeder file can help to seed dummy data for testing and also to seed some configurations in the database.</p>
</li>
<li><p><code>--requests</code> or <code>-R</code>This option generates a form request class and uses them in the controller file for the request validation.</p>
</li>
<li><p><code>--all</code>: This option is a shorthand for generating the model, <strong>migration</strong>, <strong>seeder</strong>, <strong>factory</strong>, <strong>policy</strong>, <strong>resource</strong> <strong>controller</strong>, and <strong>form</strong> <strong>request</strong> classes for the model all at once. It saves time by generating all the necessary files for a complete CRUD operation in a single command.</p>
<p> Example :</p>
<ol>
<li><p><code>php artisan make:model ModelName --all</code> will create the below files.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688755109451/96e3d510-bb92-4c25-9bee-09da7bcc0a6a.png" alt class="image--center mx-auto" /></p>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
</ol>
<hr />
<ol>
<li><p>Use case scenarios</p>
<ol>
<li><p>Certainly! To optimize the generation of classes using the available options, it's important to consider the specific requirements of your project. Here are some examples of how you can combine the options to generate classes more efficiently:</p>
<ol>
<li><p>Generating a Model, Migration, and Controller:</p>
<p> This command generates a model class, a migration file, and a controller class, all in one go. This is useful when you need to quickly set up the basic components for a new resource.</p>
<pre><code class="lang-powershell"> php artisan make:model ModelName <span class="hljs-literal">-mcr</span>
</code></pre>
</li>
<li><p>Generating a Model, Migration, and API resource Controller:</p>
<p> This command generates a model class, a migration file, and an API resource controller class, all in one go. This is useful when you need to quickly set up the basic CRUD components for API.</p>
<pre><code class="lang-powershell"> php artisan make:model ModelName <span class="hljs-literal">-mcr</span> -<span class="hljs-literal">-api</span>
</code></pre>
</li>
<li><p>You can combine any of the options explained above to create the Class files required in your CRUD and you don't need to worry about the Naming Convention and file folder structure Laravel will do that for you.</p>
</li>
</ol>
</li>
</ol>
</li>
</ol>
<hr />
<p><strong>Conclusion :</strong></p>
<p>Laravel provides convenient and efficient ways to generate model classes and associated files using the <code>php artisan make:model</code> command. By utilizing the available options, such as <strong>migrations</strong>, <strong>controllers</strong>, <strong>factories</strong>, <strong>resources</strong>, and more, developers can streamline the process of creating CRUD functionality in their applications. This helps to save time, adhere to naming conventions, and maintain a consistent project structure. By leveraging Laravel's built-in tools and conventions, developers can focus more on implementing business logic and delivering high-quality applications.</p>
]]></content:encoded></item><item><title><![CDATA[Laravel Models: Unleashing the Power of Properties]]></title><description><![CDATA[Introduction

The model in Laravel represents a logical abstraction of a database table. It acts as an intermediary between the application and the database, Laravel follows the convention of one model per table, making it easy to organize and manage...]]></description><link>https://blog.jhaabhishek.com/laravel-models-unleashing-the-power-of-properties</link><guid isPermaLink="true">https://blog.jhaabhishek.com/laravel-models-unleashing-the-power-of-properties</guid><category><![CDATA[Laravel]]></category><category><![CDATA[laravelframework]]></category><category><![CDATA[Model]]></category><category><![CDATA[mvc]]></category><category><![CDATA[laravelmodel]]></category><dc:creator><![CDATA[Abhishek Jha]]></dc:creator><pubDate>Mon, 26 Jun 2023 08:11:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1687767022334/413e8814-e29b-4c17-8249-2da709b66308.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction"><strong>Introduction</strong></h3>
<ul>
<li><p>The model in Laravel represents a logical abstraction of a database table. It acts as an intermediary between the application and the database, Laravel follows the convention of one model per table, making it easy to organize and manage your application's data.</p>
<p>  As of now, we know that for every table, we have to create a mode and models are very powerful and have lots of properties and methods to make development easier, we will explore the model's property and their use cases in this blog.</p>
</li>
</ul>
<h3 id="heading-defining-a-model"><strong>Defining a Model</strong></h3>
<ul>
<li><p>To create a model in Laravel, you can use the artisan command-line tool or manually generate a new PHP class.</p>
<p>  Command to create a model <code>php artisan make:model</code> ModelName (Use PascalCase for the model name)</p>
<p>  I prefer to create a model using the artisan command as after that I don’t have to take care of the parent model class and there are other options also available to create files that will require to complete the feature like <strong>Controller</strong>, <strong>Migration</strong>, <strong>Seeder</strong>, <strong>Factory</strong>, <strong>Request</strong>, etc.</p>
</li>
</ul>
<h3 id="heading-model-properties"><strong>Model Properties</strong></h3>
<p>Let's explore some essential properties of Laravel  models</p>
<ol>
<li><p><strong>Table Name</strong></p>
<p> By default, Laravel assumes that the table name corresponds to the snake case plural form of your model name.</p>
<p> <strong>Example</strong></p>
<ol>
<li><p>If you have a model named <code>User</code> Laravel Laravel will assume that the corresponding table name is <code>users</code> and for <code>ProductCategory</code> the table name will be <code>product_categories</code>.</p>
</li>
<li><p>You can also override this and assign the custom table name of your choice to the model’s <code>$table</code> property.</p>
<p> <code>protected $table = 'your_table_name';</code></p>
</li>
</ol>
</li>
<li><p><strong>Primary Key</strong></p>
<p> Laravel assumes the primary key of a table to be an auto-incrementing integer column named id. You can customize this behavior by setting the <code>protected $primaryKey</code> property in your model.</p>
</li>
<li><p><strong>Timestamps</strong></p>
<p> Laravel provides built-in support for maintaining <code>CREATED_AT</code> and  <code>UPDATED_AT</code>  timestamps on your model's records.</p>
<p> By default, these columns are assumed to exist in your table. However, you can disable timestamps by setting <code>public $timestamps = false</code> them in your model.</p>
<p> You can also override these column names by defining constants on your model,</p>
<p> you need to define constants <code>CREATED_AT</code> or <code>UPDATED_AT</code></p>
</li>
<li><p><strong>Soft delete</strong></p>
<p> Soft deletion in Laravel is a feature that allows you to mark records as "deleted" without actually removing them from the database.</p>
<p> By default, Laravel uses the ‘deleted_at` column <strong>(column is of type DateTime)</strong>, you can override the column name by just defining a constant with the name ‘DELETED_AT` and assigning the custom column name.</p>
</li>
<li><p><strong>Fillable and Gaurded</strong></p>
<p> To protect against mass assignment vulnerabilities, Laravel offers two approaches: fillable and guarded attributes.</p>
<p> Fillable attributes define the fields that can be mass-assigned using the <code>create()</code> or <code>update()</code> methods, while guarded attributes protect fields that should not be mass-assigned.</p>
</li>
<li><p><strong>Relationship Declarations</strong></p>
<p> Laravel simplifies working with relational databases by providing eloquent relationships.</p>
<p> You can define relationships between models using methods like <code>hasOne()</code>, <code>hasMany()</code>, <code>belongsTo()</code>, <code>belongsToMany()</code>, and more.</p>
<p> These relationships enhance data retrieval and simplify querying related data.</p>
</li>
<li><p><strong>Model Events</strong></p>
<p> Laravel models allow you to define event callbacks for various actions, such as <strong>creating</strong>, <strong>updating</strong>, <strong>deleting</strong>, and <strong>retrieving</strong> records. These events provide hooks into the model's lifecycle and enable you to execute custom logic when specific actions occur.</p>
</li>
<li><p><strong>Connection</strong></p>
<p> By default, Laravel assumes that a model will use the default database connection specified in the <code>config/database.php</code> configuration file.</p>
<p> However, there are cases where you may need to connect to a different database or use a specific connection for a particular model. In such scenarios, you can set the <code>$connection</code> property within your model class to specify the desired database connection.</p>
<p> <code>protected $connection = 'your_connection_name';</code></p>
</li>
<li><p><strong>Recently Created</strong></p>
<p> The <code>public $wasRecentlyCreated</code> property in Laravel is a flag that indicates whether a model instance was recently created and saved to the database.</p>
</li>
<li><p><strong>Model exists</strong></p>
<p>The <code>public $exists</code> property in Laravel is a flag that indicates whether a model instance exists in the database.</p>
<p>You may have a model instance that does not correspond to an actual record in the database. In such cases, you can manually set the <code>$exists</code> property to <strong>false</strong> to indicate that the model instance does not exist in the database.</p>
</li>
<li><p><strong>Global Scope</strong></p>
<p>The <code>protected static $globalScopes</code> property in Laravel allows you to define global scopes for your Eloquent models.</p>
<p>Global scopes are conditions that are automatically applied to all queries for a given model. They enable you to define common query constraints that should be applied to every database interaction for that model.</p>
<p>The <code>$globalScopes</code> property is an array where you can define instances of your global scope classes. Each entry in the array represents a global scope that you want to apply to the model.</p>
</li>
<li><p><strong>Pagination</strong></p>
<p>The <code>protected $perPage</code> property in Laravel allows you to specify the default number of items to be included in a paginated result set.</p>
<p>When you retrieve a collection of models and paginate the results using Laravel's pagination feature, the <code>$perPage</code> property determines the number of items that will be displayed per page. By default the value per page value sets to 15, you can modify that on your model by <code>protected $perPage = 30;</code></p>
</li>
</ol>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<ul>
<li>Laravel models are the backbone of database interaction in your web applications. By leveraging the Eloquent ORM, developers can streamline database operations, define relationships between entities, and implement complex querying with ease. Understanding the various properties and features of Laravel models empowers developers to build robust and maintainable applications efficiently.</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Types of Controllers in Laravel]]></title><description><![CDATA[Controllers are an essential part of web development, particularly when working with the Laravel framework. Laravel offers four types of controllers Basic Controllers, Resource Controllers, API Controllers, and Invokable Controllers. In this blog, we...]]></description><link>https://blog.jhaabhishek.com/types-of-controllers-in-laravel</link><guid isPermaLink="true">https://blog.jhaabhishek.com/types-of-controllers-in-laravel</guid><category><![CDATA[Laravel]]></category><category><![CDATA[laravelframework]]></category><category><![CDATA[mvc]]></category><category><![CDATA[controllers]]></category><category><![CDATA[LaravelController]]></category><dc:creator><![CDATA[Abhishek Jha]]></dc:creator><pubDate>Wed, 21 Jun 2023 12:47:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1687351419851/e481afc3-8f6b-4af8-94ea-759e8c29cfc1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Controllers are an essential part of web development, particularly when working with the Laravel framework. Laravel offers four types of controllers <strong>Basic Controllers</strong>, <strong>Resource Controllers</strong>, <strong>API Controllers</strong>, and <strong>Invokable Controllers</strong>. In this blog, we will explore each type and delve into their specific use cases.</p>
<ol>
<li><p><strong>Basic Controllers:</strong></p>
<p> Basic Controllers are the simplest form of controllers in Laravel. They contain methods that handle various HTTP requests, such as GET, POST, PUT, and DELETE. These controllers are useful when you have a small number of routes and actions to manage. They provide a straightforward way to organize your application logic without any additional complexity. Basic Controllers are often used in smaller projects or when the logic for each route action is minimal.</p>
<p> Command to create a basic controller: <code>php artisan make:controller ControllerName</code></p>
</li>
<li><p><strong>Resource Controllers:</strong></p>
<p> Resource Controllers are designed to handle the common CRUD (Create, Read, Update, Delete) operations for a specific resource. Laravel's resource routing feature allows you to define these controllers with a single line of code, which automatically generates the necessary routes for all the standard RESTful actions. Resource Controllers provide a clean and consistent way to handle data manipulation in your application. They are ideal for managing resources such as articles, users, or products.</p>
<p> Command to create a resource controller: <code>php artisan make:controller ControllerName -r</code>(Resource)</p>
</li>
<li><p><strong>API Controllers:</strong></p>
<p> API Controllers are specifically tailored for building APIs or web services. They typically return JSON or XML responses instead of rendering views. API Controllers are useful when you need to expose your application's functionality to other systems or integrate with mobile apps. These controllers often involve authentication, validation, and serialization of data. Laravel provides tools and middleware to simplify these tasks, making API development more streamlined.</p>
<p> Command to create a resource controller: <code>php artisan make:controller ControllerName --api</code></p>
<p> <strong>Note:</strong> This will create a Resource controller for API and <code>create</code> and <code>edit</code> methods will be excluded as we don't need these methods in API.</p>
</li>
<li><p><strong>Invokable Controllers:</strong></p>
<p> Invokable Controllers are a unique feature of Laravel that allows you to define a controller as a single, callable class. Instead of having multiple methods to handle different actions, an invokable controller has a single <code>__invoke()</code> method that handles the request. This approach provides a clean and concise way to define controller logic when you have a single action to perform. Invokable Controllers are particularly useful for tasks such as processing form submissions or executing a specific operation.</p>
</li>
</ol>
<p>Command to create a resource controller: <code>php artisan make:controller ControllerName -i</code></p>
<h3 id="heading-conclusion"><strong>Conclusion:</strong></h3>
<p>Laravel's flexibility allows you to mix and match these controller types as your project evolves and grows in complexity. Stay mindful of the specific use cases for each type and adapt them accordingly to build scalable and efficient web applications.</p>
]]></content:encoded></item></channel></rss>