<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rautbibek on Medium]]></title>
        <description><![CDATA[Stories by Rautbibek on Medium]]></description>
        <link>https://medium.com/@rautbibek47?source=rss-5b35b6159daa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oo0a6uIP3MJlfoysOZPoog@2x.jpeg</url>
            <title>Stories by Rautbibek on Medium</title>
            <link>https://medium.com/@rautbibek47?source=rss-5b35b6159daa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:09:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rautbibek47/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Laravel Query Builder vs Eloquent]]></title>
            <link>https://medium.com/@rautbibek47/laravel-query-builder-vs-eloquent-10abc522cb6a?source=rss-5b35b6159daa------2</link>
            <guid isPermaLink="false">https://medium.com/p/10abc522cb6a</guid>
            <category><![CDATA[php-programming]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[eloquent]]></category>
            <category><![CDATA[query-builder]]></category>
            <dc:creator><![CDATA[Rautbibek]]></dc:creator>
            <pubDate>Fri, 13 Feb 2026 17:13:10 GMT</pubDate>
            <atom:updated>2026-02-13T17:13:10.224Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ncxEXp5OSEADlajGLDcO1Q.png" /><figcaption>Laravel Query Builder vs Eloquent</figcaption></figure><p><strong><em>When to Use What (And Why Most Developers Choose Wrong)</em></strong></p><p>Laravel gives developers two primary ways to interact with the database:</p><ol><li><strong>Eloquent ORM</strong></li><li><strong>Query Builder</strong></li></ol><p>Both generate SQL.<br>Both are powerful.<br>Both are misunderstood.</p><p>Most developers don’t actually choose between them<br>they default to Eloquent for everything… and that is exactly where performance problems begin.</p><p>This article is not about which is better.</p><p>It’s about:</p><blockquote><em>Using the right tool for the right problem.</em></blockquote><h3>First: What is the Real Difference?</h3><h4>Eloquent ORM</h4><p>Eloquent is an <strong>Active Record ORM</strong>.<br>Each database table is represented as a PHP class (Model).</p><pre>$order = Order::with(&#39;customer&#39;)-&gt;find(1);<br>echo $order-&gt;customer-&gt;name;</pre><p>You are working with objects, not rows.</p><p><strong>Eloquent provides:</strong></p><ul><li>Relationships</li><li>Accessors/Mutators</li><li>Events</li><li>Scopes</li><li>Attribute casting</li><li>Business logic inside models</li></ul><p>It is a database<strong> + </strong>domain logic combined.</p><h4>Query Builder</h4><p>Query Builder is a SQL abstraction layer.</p><p>It does not care about Models, Relationships, or Business Logic.</p><pre>$order = DB::table(&#39;orders&#39;)<br>    -&gt;join(&#39;customers&#39;, &#39;customers.id&#39;, &#39;=&#39;, &#39;orders.customer_id&#39;)<br>    -&gt;select(&#39;orders.id&#39;, &#39;customers.name&#39;)<br>    -&gt;where(&#39;orders.id&#39;, 1)<br>    -&gt;first();</pre><p>You are working with <strong>raw database rows</strong>.</p><p>Query Builder provides:</p><ul><li>Faster execution</li><li>Fine SQL control</li><li>Complex joins</li><li>Aggregates</li><li>Bulk operations</li></ul><p>It is database access only.</p><h3>What Most Developers Don’t Realize</h3><p>Eloquent is built <strong>on top of Query Builder</strong>.</p><p>Meaning:</p><blockquote>Every Eloquent query eventually becomes a Query Builder query → then SQL.</blockquote><p>So the real difference is not SQL.</p><p>The real difference is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*OvfHXTQiuJRQ_CrJazrgmw.png" /><figcaption>Table 1.1</figcaption></figure><h4>Best Case for Eloquent (Where It Shines)</h4><p>Eloquent is NOT for data retrieval.</p><p>It is for domain modeling.</p><p><strong>Use Eloquent when:</strong></p><h4>1) Relationships Matter</h4><pre>$orders = Order::with([&#39;customer&#39;,&#39;items.product&#39;])-&gt;get();</pre><p>This is where Eloquent is unbeatable.</p><p>You get:</p><ul><li>Clean code</li><li>Maintainability</li><li>Readability</li></ul><p>Writing this in Query Builder becomes ugly and fragile.</p><h4>2) Business Logic Belongs to Data</h4><p>Example:</p><pre>class Order extends Model<br>{<br>    public function getIsPaidAttribute()<br>    {<br>        return $this-&gt;payment_status === &#39;paid&#39;;<br>    }<br>}</pre><p>Now anywhere:</p><pre>if($order-&gt;is_paid) { ... }</pre><p>That is not SQL anymore.<br>That is <strong>business behavior</strong>.</p><p>Query Builder cannot do this.</p><h4>3) Application CRUD (Admin Panels, APIs)</h4><ul><li>Create order</li><li>Update profile</li><li>Save invoice</li><li>Update settings</li></ul><pre>$user-&gt;update([&#39;name&#39;=&gt;&#39;Bibek&#39;]);</pre><p>This is exactly what Eloquent is designed for.</p><h4>Worst Case for Eloquent (X)</h4><p>This is where many Laravel apps die.</p><h4>1) Large Reports</h4><p><em>Bad Example</em></p><pre>Order::with(&#39;customer&#39;,&#39;items&#39;,&#39;payments&#39;)-&gt;get();</pre><p>If orders = 80,000</p><p>You just:</p><ul><li>Hydrated 80k objects</li><li>Hydrated nested relations</li><li>Allocated massive memory</li><li>Slowed PHP execution</li></ul><p>This is NOT a database problem.</p><p>This is a <strong>PHP memory problem</strong>.</p><p>Eloquent is loading objects.<br>Not rows.</p><h4>2) Aggregates</h4><pre>Order::sum(&#39;total&#39;);<br>Order::count();<br>Order::groupBy(&#39;status&#39;)-&gt;get();</pre><p>&quot;Eloquent&quot; is unnecessary here.</p><p>No domain logic is needed.</p><p>You are asking the database to calculate, not PHP.</p><h4>Use Query Builder.</h4><h4>3) Bulk Updates</h4><p>Worst possible thing:</p><pre>$orders = Order::where(&#39;status&#39;,&#39;pending&#39;)-&gt;get();</pre><pre>foreach($orders as $order){<br>    $order-&gt;update([&#39;status&#39;=&gt;&#39;expired&#39;]);<br>}</pre><p>You just ran:<br> N queries + N model hydration + N events</p><p>Production killer.</p><h4>Best Case for Query Builder</h4><p>Query Builder is a <strong>data processing tool</strong>, not a business logic tool.</p><p>Use it when the database should do the heavy lifting.</p><h4>1) Reports &amp; Dashboards</h4><p>Example:</p><ul><li>sales reports</li><li>analytics</li><li>charts</li><li>statistics</li><li>exports</li></ul><pre>DB::table(&#39;orders&#39;)<br>    -&gt;selectRaw(&#39;DATE(created_at) as date, SUM(total) as total&#39;)<br>    -&gt;groupBy(&#39;date&#39;)<br>    -&gt;get();</pre><p>Database engines are optimized for this.</p><p>PHP is not.</p><h4>2) Bulk Operations</h4><pre>DB::table(&#39;orders&#39;)<br>  -&gt;where(&#39;status&#39;,&#39;pending&#39;)<br>  -&gt;update([&#39;status&#39;=&gt;&#39;expired&#39;]);</pre><p>Single query.<br>Milliseconds.</p><h4>3) Joins Across Many Tables</h4><p>Eloquent relations start breaking down when joins grow complex.</p><p>Example:</p><ul><li>invoices</li><li>payments</li><li>refunds</li><li>currencies</li><li>tax tables</li></ul><p>Query Builder handles this cleanly.</p><h4>Worst Case for Query Builder (X)</h4><h4>1) Complex Business Rules</h4><p>You will end up writing:</p><ul><li>repeated code</li><li>duplicated logic</li><li>maintenance nightmare</li></ul><pre>if($order-&gt;payment_status === &#39;paid&#39; &amp;&amp; $order-&gt;shipped_at !== null)</pre><p>You just moved domain logic into controllers.</p><h4>2) APIs / Resource Models</h4><p>Without Eloquent:</p><ul><li>No casting</li><li>No accessors</li><li>No relationships</li><li>No scopes</li></ul><p>Your controllers become 1000 lines.</p><h4>The Real Rule (Important)</h4><blockquote><em>Eloquent = Behavior<br>Query Builder = Data</em></blockquote><p>Or even simpler:</p><blockquote><strong>If you are modeling your application → Eloquent</strong><br><strong>If you are querying your database → Query Builder</strong></blockquote><h4>The Hybrid Strategy</h4><p>Good Laravel applications <strong>use both together</strong>.</p><p>Example:</p><ul><li>Use Eloquent for orders</li><li>Use Query Builder for reports</li></ul><pre>$orders = Order::with(&#39;customer&#39;)-&gt;paginate(20); // Eloquent<br>$report = DB::table(&#39;orders&#39;)-&gt;selectRaw(&#39;SUM(total)&#39;)-&gt;first(); // Query Builder</pre><p>This is not breaking Laravel philosophy.</p><p>This <em>is</em> Laravel philosophy.</p><h4>Quick Decision Guide</h4><figure><img alt="Table 1.2" src="https://cdn-images-1.medium.com/max/862/1*xBKhYW8WzV1OWbp2I3EYMg.png" /><figcaption>Table 1.2</figcaption></figure><h4>Final Thought</h4><p>Eloquent is beautiful.</p><p>Query Builder is powerful.</p><p>But performance problems in Laravel rarely come from MySQL or PostgreSQL.</p><p>They come from:</p><blockquote><em>Using Eloquent as a reporting engine.</em></blockquote><p>Laravel didn’t design Eloquent to replace SQL.</p><p>It designed Eloquent to model your application.</p><p>Once you understand that distinction, your applications become:</p><ul><li>faster</li><li>cleaner</li><li>scalable</li></ul><p>And suddenly…<br>Laravel feels like a senior-level framework.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10abc522cb6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upload, Resize, and Canvas Images in Laravel Using Intervention Image v3 (The Right Way)]]></title>
            <link>https://medium.com/@rautbibek47/upload-resize-and-canvas-images-in-laravel-using-intervention-image-v3-the-right-way-3e80d0db15cc?source=rss-5b35b6159daa------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e80d0db15cc</guid>
            <category><![CDATA[resize]]></category>
            <category><![CDATA[resize-images]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[image-upload]]></category>
            <category><![CDATA[intervention-image]]></category>
            <dc:creator><![CDATA[Rautbibek]]></dc:creator>
            <pubDate>Sat, 14 Jun 2025 09:09:30 GMT</pubDate>
            <atom:updated>2025-06-14T09:09:30.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*zjGMScIPMENdj4xIo_isPA.jpeg" /></figure><p>Handling image uploads is a core part of many Laravel applications — whether you’re building user profiles, product galleries, or content-driven sites. Inconsistent image dimensions can cause layout issues, poor thumbnails, and messy UI.</p><p>In this tutorial, I’ll show you how to:</p><p>✅ Upload an image in Laravel<br> ✅ Resize it while maintaining aspect ratio<br> ✅ Canvas it to a perfect square<br> ✅ Generate a thumbnail<br> ✅ Throw a custom exception if the image is too small</p><p>We’ll use <strong>Intervention Image v3</strong>, the latest version of the popular image manipulation library.</p><h4>Install Intervention Image v3</h4><pre>composer require intervention/image-laravel<br><br>php artisan vendor:publish provider=&quot;Intervention\Image\Laravel\ServiceProvider&quot;</pre><p>For more detailed installation steps, please refer to the official documentation available <a href="https://image.intervention.io/v3/getting-started/frameworks">here</a></p><h4>Image Processing Logic</h4><p>Here’s what our function will do:</p><ul><li>Accept an uploaded image</li><li>If either width or height is <strong>greater than 1000px</strong>, resize proportionally based on the dominant dimension</li><li>Add white canvas space to make the image exactly <strong>1000x1000px</strong></li><li>Generate a <strong>100x100 thumbnail</strong></li><li>Save both images using Laravel’s storage system</li></ul><h4>Full Code</h4><pre>public function storeResizedImage($file)<br>{<br>    $filename = date(&#39;mdYHis&#39;) . uniqid() . &#39;.&#39; . $file-&gt;getClientOriginalExtension();<br>    $image = Image::read($file);<br>    $width = $image-&gt;width();<br>    $height = $image-&gt;height();<br>    $finalSize = 1000;<br>    $thumbnailSize = 100;<br><br>    // Only process if either dimension is greater than 1000<br><br>    if ($width &gt; $finalSize || $height &gt; $finalSize) {<br>        if ($width &gt; $height) {<br>            $image-&gt;scale(width: $finalSize);<br>        } elseif ($height &gt; $width) {<br>            $image-&gt;scale(height: $finalSize);<br>        } else {<br>            // square image, scale on either<br>            $image-&gt;scale(height: $finalSize);<br>        }<br><br>        // Ensure canvas is a perfect 1000x1000 square<br>        $image-&gt;resizeCanvas($finalSize, $finalSize, &#39;#ffff&#39;, &#39;center&#39;);<br><br>    } else {<br>        //place your logic here if you don`t want to throw an exception<br>        throw new CustomException(&#39;Image size is too small. Minimum width or height should be greater than 1000 pixels.&#39;);<br>    }<br><br>    // Save full-size image<br>    Storage::put(&#39;uploads/&#39; . $filename, (string) $image-&gt;encode());<br><br>    // Create and save 100x100 thumbnail<br>    $thumbnail = $image-&gt;scale(height: $thumbnailSize);<br>    Storage::put(&#39;thumb/&#39; . $filename, (string) $thumbnail-&gt;encode());<br><br>    return $filename;<br>}</pre><h3>Example Controller Use</h3><p>Here’s how you might integrate this into your controller:</p><pre>public function upload(Request $request)<br>{<br>    $request-&gt;validate([<br>        &#39;image&#39; =&gt; &#39;required|image|max:5120&#39;, // 5MB max<br>    ]);<br>  $filename = $this-&gt;storeResizedImage($request-&gt;file(&#39;image&#39;));<br>    return response()-&gt;json([<br>        &#39;message&#39; =&gt; &#39;Image uploaded successfully!&#39;,<br>        &#39;filename&#39; =&gt; $filename<br>    ]);<br>}</pre><p><strong>How It Works (Step-by-Step)</strong></p><ul><li>Accept the uploaded image file.</li><li>Check if either the width or height is greater than 1000 pixels.</li><li>If both dimensions are 1000px or less, throw a CustomException saying the image is too small.</li><li>If the image is valid:</li><li>If the width is greater than the height, scale the image based on the width to 1000px.</li><li>If the height is greater than the width, scale the image based on the height to 1000px.</li><li>If width and height are equal, scale by either dimension (height in this case).</li><li>After scaling, apply a white canvas to make the image exactly 1000x1000 pixels, centered.</li><li>Save the full-sized processed image to the uploads/ directory.</li></ul><p>Generate a 100x100 thumbnail by scaling the same image, and save it to the thumb/ directory.</p><h3>Conclusion</h3><p>This approach ensures that your uploaded images are <strong>standardized, square, and high-quality</strong> — with minimal distortion. Combined with Laravel’s filesystem and validation features, you get a powerful and flexible image upload system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e80d0db15cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mixins vs Composables in Vue]]></title>
            <link>https://medium.com/@rautbibek47/mixins-vs-composables-in-vue-f44c8125019a?source=rss-5b35b6159daa------2</link>
            <guid isPermaLink="false">https://medium.com/p/f44c8125019a</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vue-mixins]]></category>
            <category><![CDATA[composables]]></category>
            <dc:creator><![CDATA[Rautbibek]]></dc:creator>
            <pubDate>Mon, 24 Jun 2024 05:29:38 GMT</pubDate>
            <atom:updated>2024-06-24T05:29:38.917Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*xhQHWa0Ue_Xv1g9AIOVEpQ.png" /></figure><p>In the world of Vue.js, managing and reusing code efficiently is crucial for building scalable applications. Two primary patterns for code reuse are Mixins and the Composition API (using Composables). With Vue 3, the Composition API has gained popularity due to its flexibility and improved code organization. In this article, we will explore both patterns, their pros and cons, and how to implement them.</p><h4>What are Mixins?</h4><p>Mixins are a way to distribute reusable functionalities for Vue components. They allow you to extract component logic into reusable pieces. Here’s a simple example:</p><pre>// mixins/helloMixin.js<br><br>export default {<br>  data() {<br>    return {<br>      message: &#39;Hello from mixin!&#39;<br>    };<br>  },<br>  methods: {<br>    greet() {<br>      console.log(this.message);<br>    }<br>  }<br>};</pre><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;p&gt;{{ message }}&lt;/p&gt;<br>    &lt;button @click=&quot;greet&quot;&gt;Greet&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>import helloMixin from &#39;./mixins/helloMixin.js&#39;;<br><br>export default {<br>  mixins: [helloMixin]<br>};<br>&lt;/script&gt;</pre><h4>Pros and Cons of Mixins</h4><h4>Pros:</h4><ol><li>Simple to Use: Mixins are straightforward to use, making them accessible for developers familiar with traditional object-oriented programming.</li><li>Inheritance-like Reuse: They provide a way to share functionality across components easily, similar to class inheritance.</li></ol><h4>Cons:</h4><ol><li>Naming Conflicts: Mixins can lead to naming conflicts and ambiguity since they merge with the component’s own methods and data.</li><li>Lack of Explicitness: The logic is less explicit, making it harder to track the origin of properties and methods.</li><li>Scalability Issues: As applications grow, managing and understanding multiple mixins can become challenging.</li></ol><h4>What are Composables?</h4><p>Composables are functions that leverage Vue 3’s Composition API to encapsulate and reuse logic. These functions can be imported and used across different components, offering better type safety and a more explicit structure.</p><p>Here’s how to achieve the same functionality as the mixin example using Composables:</p><pre>// composables/useHello.js<br>import { ref } from &#39;vue&#39;;<br><br>export function useHello() {<br>  const message = ref(&#39;Hello from composable!&#39;);<br>  const greet = () =&gt; {<br>    console.log(message.value);<br>  };<br><br>  return {<br>    message,<br>    greet<br>  };<br>}</pre><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;p&gt;{{ message }}&lt;/p&gt;<br>    &lt;button @click=&quot;greet&quot;&gt;Greet&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import { useHello } from &#39;./composables/useHello.js&#39;;<br><br>const { message, greet } = useHello();<br>&lt;/script&gt;</pre><h4>Pros and Cons of Composables</h4><h4>Pros:</h4><ol><li>Explicit Logic: Composables provide a clear and explicit way to organize and reuse logic, making the codebase easier to understand and maintain.</li><li>Better Type Safety: TypeScript integration with the Composition API is more straightforward, enhancing type safety.</li><li>Flexible and Modular: Composables are highly modular, allowing for better organization and reuse of code across different parts of the application.</li></ol><h4>Cons:</h4><ol><li>Learning Curve: The Composition API introduces new concepts that can be challenging for developers who are accustomed to the Options API.</li><li>Boilerplate Code: Initial setup of Composables might feel like additional boilerplate compared to mixins.</li></ol><h3>Conclusion</h3><p>Both Mixins and Composables have their place in Vue development. Mixins provide a quick and simple way to reuse logic, but they can lead to issues with scalability and maintainability. Composables, on the other hand, offer a more explicit, flexible, and type-safe approach, especially suitable for larger applications.</p><p>With Vue 3, the Composition API and Composables are recommended due to their modularity and clarity. The &lt;script setup&gt; syntax further simplifies the use of Composables, making the code cleaner and more efficient. As the ecosystem evolves, embracing Composables will likely lead to more maintainable and scalable Vue applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f44c8125019a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Your API Calls with Axios Interceptors]]></title>
            <link>https://medium.com/@rautbibek47/enhancing-your-api-calls-with-axios-interceptors-6db824a9621a?source=rss-5b35b6159daa------2</link>
            <guid isPermaLink="false">https://medium.com/p/6db824a9621a</guid>
            <category><![CDATA[axios-interceptor]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Rautbibek]]></dc:creator>
            <pubDate>Fri, 31 May 2024 17:08:30 GMT</pubDate>
            <atom:updated>2024-05-31T17:08:30.849Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DfXj70PID4YvRZAjXCr4Rg.png" /></figure><p>In modern web development, handling HTTP requests efficiently and gracefully managing responses and errors is crucial for building robust applications. Axios, a popular HTTP client for JavaScript, provides powerful features to help with this, including interceptors. Interceptors allow you to define functions to run before a request is sent or after a response is received, providing a centralized place to handle common tasks like adding authentication headers or managing error responses.</p><p>In this article, we’ll explore how to set up Axios interceptors by walking through an example code implementation. We’ll discuss how to configure request and response interceptors to streamline your API interactions.</p><h4>Setting Up Axios</h4><p>First, let’s set up an Axios instance with a base URL. This is where we’ll configure our interceptors.</p><pre>import axios from &quot;axios&quot;;<br><br>const axiosClient = axios.create({<br>    baseURL: process.env.API_BASE_URL,<br>});</pre><p>Here, we create a new Axios instance with a base URL defined in an environment variable. This ensures that all requests made using this instance are prefixed with the base URL, keeping our API endpoints organized and easily configurable.</p><h4>Request Interceptor</h4><p>A request interceptor allows us to modify requests before they are sent. In this example, we add an Accept header and an optional Authorization header to every request.</p><pre>const requestHandler = (request) =&gt; {<br>    request.headers.Accept = &quot;application/json&quot;;<br>    request.headers.Authorization = `Bearer ${token}`;<br>    // Add or remove this line based on your requirement<br>    return request;<br>};<br><br>axiosClient.interceptors.request.use(<br>    (request) =&gt; requestHandler(request),<br>    (error) =&gt; Promise.reject(error)<br>);</pre><p>The requestHandler function adds necessary headers to the request. Depending on your needs, you can include or exclude the Authorization header, which typically carries a bearer token used for authentication. By using an interceptor, we ensure that these headers are included in every request without having to manually add them each time.</p><h4>Response Interceptor</h4><p>A response interceptor lets us handle responses globally. In this example, we handle successful responses and manage different error scenarios.</p><pre>const responseHandler = (response) =&gt; {<br>    if (response?.data?.message) {<br>        // Notify user of the success message<br>    }<br>    return response;<br>};<br><br>const errorHandler = (error) =&gt; {<br>    if (error.response?.status === 401) {<br>        // Handle unauthorized access, e.g., redirect to login<br>    } else {<br>        // Notify user of other errors<br>    }<br>    if (error.response?.status === 500) {<br>        // Handle server errors<br>    }<br>    return Promise.reject(error);<br>};<br><br>axiosClient.interceptors.response.use(<br>    (response) =&gt; responseHandler(response),<br>    (error) =&gt; errorHandler(error)<br>);</pre><p>The responseHandler function checks if there&#39;s a message in the response data and could, for instance, display a notification to the user. The errorHandler function handles various error scenarios:</p><ul><li>401 Unauthorized: Handle unauthorized access, such as by redirecting the user to the login page.</li><li>Other Errors: Notify the user of other types of errors.</li><li>500 Internal Server Error: Handle server errors.</li></ul><p>These interceptors ensure that all responses and errors are handled consistently across your application, improving maintainability and user experience. If you need to perform specific actions based on different error codes, this is the place to do it.</p><h3>Putting It All Together</h3><p>Here’s the complete code with both request and response interceptors configured:</p><pre>import axios from &quot;axios&quot;;<br><br>const axiosClient = axios.create({<br>    baseURL: process.env.API_BASE_URL,<br>});<br><br>const requestHandler = (request) =&gt; {<br>    request.headers.Accept = &quot;application/json&quot;;<br>    request.headers.Authorization = `Bearer ${token}`;<br>    // Add or remove this line based on your requirement<br>    return request;<br>};<br><br>const responseHandler = (response) =&gt; {<br>    if (response?.data?.message) {<br>        // Notify user of the success message<br>    }<br>    return response;<br>};<br><br>const errorHandler = (error) =&gt; {<br>    if (error.response?.status === 401) {<br>        // Handle unauthorized access, e.g., redirect to login<br>    }<br>    if (error.response?.status === 500) {<br>        // Handle server errors<br>    }<br>    return Promise.reject(error);<br>};<br><br>axiosClient.interceptors.request.use(<br>    (request) =&gt; requestHandler(request),<br>    (error) =&gt; Promise.reject(error)<br>);<br><br>axiosClient.interceptors.response.use(<br>    (response) =&gt; responseHandler(response),<br>    (error) =&gt; errorHandler(error)<br>);<br><br>export {axiosClient};</pre><p>By using Axios interceptors, you can simplify and centralize the handling of requests and responses, making your code cleaner and more maintainable. This approach ensures that all API interactions are consistently managed, enhancing the robustness of your application.</p><p>Feel free to customize these interceptors to suit your specific needs, such as adding more sophisticated error handling or logging mechanisms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6db824a9621a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Composition API vs Options API: Choosing the Right Approach in Vue.js Development]]></title>
            <link>https://medium.com/@rautbibek47/composition-api-vs-options-api-choosing-the-right-approach-in-vue-js-development-87287f0bf726?source=rss-5b35b6159daa------2</link>
            <guid isPermaLink="false">https://medium.com/p/87287f0bf726</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[options-api]]></category>
            <category><![CDATA[vue-3]]></category>
            <category><![CDATA[vue-knowledge]]></category>
            <category><![CDATA[composition-api]]></category>
            <dc:creator><![CDATA[Rautbibek]]></dc:creator>
            <pubDate>Wed, 29 May 2024 11:50:19 GMT</pubDate>
            <atom:updated>2024-05-29T11:50:19.048Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ErXYR47E2OP1g_zQ7eW4ug.png" /></figure><p>Vue.js, with its progressive framework and intuitive design, offers developers multiple ways to structure and organize their code. The two primary approaches for building Vue components are the Options API and the Composition API. Each approach has its strengths and use cases, and understanding the differences between them is crucial for making informed decisions in Vue.js development. In this article, we’ll explore the Composition API and the Options API, comparing their features, benefits, and scenarios where each shines.</p><h4>Options API</h4><p>The Options API is the traditional approach to structuring Vue components. It relies on object-based component options, where each option corresponds to a specific aspect of the component, such as data, methods, computed properties, and lifecycle hooks.</p><blockquote><strong><em>Key Features:</em></strong></blockquote><ul><li><strong>Declarative Syntax</strong>: The Options API provides a straightforward and declarative syntax for defining component options, making it easy to understand and maintain.</li><li><strong>Separation of Concerns</strong>: Components built with the Options API naturally separate concerns by organizing data, methods, and lifecycle hooks into distinct sections.</li><li><strong>Widely Adopted</strong>: The Options API is well-established and widely adopted, making it familiar to many Vue.js developers and readily available in tutorials and documentation.</li></ul><blockquote><strong><em>Use Cases:</em></strong></blockquote><ul><li><strong>Small to Medium-sized Components</strong>: The Options API is well-suited for building small to medium-sized components with straightforward logic and lifecycle requirements.</li><li><strong>Rapid Prototyping</strong>: Its simplicity and familiarity make the Options API ideal for rapid prototyping and quick development iterations.</li></ul><h4>Composition API</h4><p>Introduced in Vue 3, the Composition API offers a more flexible and powerful approach to building Vue components by enabling composition of logic using functions. It encourages code reuse, organization, and better separation of concerns.</p><blockquote><strong><em>Key Features:</em></strong></blockquote><ul><li><strong>Function-based Composition</strong>: Components built with the Composition API are composed of functions that encapsulate logic and state, promoting better code organization and reusability.</li><li><strong>Composable and Reactive</strong>: The Composition API allows developers to create composable functions that can be reused across multiple components, leading to more modular and maintainable codebases.</li><li><strong>Improved TypeScript Support</strong>: With its function-based approach, the Composition API provides better support for TypeScript, offering improved type inference and code safety.</li></ul><blockquote><strong><em>Use Cases:</em></strong></blockquote><ul><li><strong>Large and Complex Components:</strong> The Composition API excels in managing the complexity of large components with multiple concerns, enabling developers to organize logic more efficiently.</li><li><strong>Code Reusability:</strong> Its composable nature makes the Composition API ideal for creating reusable logic that can be shared across multiple components, reducing duplication and improving maintainability.</li><li><strong>TypeScript Projects</strong>: Developers working on TypeScript projects can leverage the Composition API’s improved support for type inference and code safety.</li></ul><h4>Choosing the Right Approach</h4><p>When deciding between the Composition API and the Options API, it’s essential to consider the specific requirements and characteristics of your project. Here are some factors to consider:</p><ul><li><strong>Project Size and Complexity</strong>: For small to medium-sized projects with straightforward logic, the Options API may suffice. However, for larger and more complex projects, the Composition API offers better scalability and organization.</li><li><strong>Developer Familiarity</strong>: If your team is already familiar with the Options API and the project requirements are relatively simple, sticking with the Options API may streamline development. However, investing in learning the Composition API can pay off in the long run, especially for larger projects.</li><li><strong>TypeScript Usage</strong>: If your project utilizes TypeScript, the Composition API provides better support and type inference, making it the preferred choice for ensuring code safety and maintainability.</li></ul><p>In conclusion, both the Composition API and the Options API have their merits, and the choice between them ultimately depends on the specific needs and characteristics of your project. While the Options API remains a reliable and straightforward choice for many scenarios, the Composition API offers more flexibility, organization, and scalability, particularly for larger and more complex projects. By understanding the strengths and trade-offs of each approach, Vue.js developers can make informed decisions that optimize productivity and code maintainability in their projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87287f0bf726" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Form Validation in Vue 3 Using Composition API ,VeeValidate and Yup]]></title>
            <link>https://medium.com/@rautbibek47/form-validation-in-vue-3-using-composition-api-veevalidate-and-yup-fad601221ac6?source=rss-5b35b6159daa------2</link>
            <guid isPermaLink="false">https://medium.com/p/fad601221ac6</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[composition-api]]></category>
            <category><![CDATA[yup]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vee-validate]]></category>
            <dc:creator><![CDATA[Rautbibek]]></dc:creator>
            <pubDate>Tue, 28 May 2024 08:56:03 GMT</pubDate>
            <atom:updated>2024-05-28T09:00:11.610Z</atom:updated>
            <content:encoded><![CDATA[<h3>Form Validation in Vue 3 Using Composition API ,VeeValidate and Yup</h3><p>Form validation is a crucial part of any web application. In this article, we will explore how to handle form validation in Vue 3 using the Composition API along with <a href="https://vee-validate.logaretm.com/v4/">VeeValidate</a> and <a href="https://www.npmjs.com/package/yup">Yup</a>. We will also create a custom input component to demonstrate how to reuse form elements effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*bOsjZretir-dQNa0-xoNFA.png" /><figcaption>validation with vee-validate and yup</figcaption></figure><h4>Introduction</h4><p>Vue 3’s Composition API offers a more flexible and organized way to manage state and logic within components. VeeValidate simplifies form validation by providing a set of powerful tools, and Yup is a JavaScript schema builder for value parsing and validation. Together, these tools make form validation in Vue 3 both powerful and easy to manage.</p><h4>Prerequisites</h4><p>To follow along with this tutorial, you should have:</p><ul><li>Basic knowledge of Vue.js</li><li>Node.js and npm installed on your machine</li></ul><h4>Setting Up the Project</h4><p>First, let’s create a new Vue 3 project:</p><pre>npm init vue@latest<br>cd your-project-name<br>npm install</pre><p>Then, install VeeValidate and Yup:</p><pre>npm install vee-validate yup</pre><h4>Creating a Custom Input Component</h4><p>Let’s start by creating a custom input component. This component will encapsulate our input logic and validation states.</p><blockquote>FileName : CustomInput.vue</blockquote><pre>&lt;template&gt;<br>  &lt;div class=&quot;wrapper&quot;&gt;<br>    &lt;label v-if=&quot;label&quot; :for=&quot;name&quot;&gt;{{ label }}&lt;/label&gt;<br>    &lt;input<br>      :id=&quot;name&quot;<br>      :class=&quot;{ field_error: errorMessage, valid: meta.valid }&quot;<br>      class=&quot;input&quot;<br>      v-model=&quot;value&quot;<br>      :placeholder=&quot;placeholder&quot;<br>      :type=&quot;type || &#39;text&#39;&quot;<br>    /&gt;<br><br>    &lt;small :class=&quot;errorMessage ? &#39;error_message&#39; : &#39;&#39;&quot;&gt;{{ errorMessage }}&lt;/small&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import { useField } from &#39;vee-validate&#39;<br><br>const props = defineProps({<br>  name: {<br>    type: String,<br>    required: true<br>  },<br>  type: String,<br>  placeholder: String,<br>  label: String<br>})<br><br>const { value, errorMessage, meta } = useField(() =&gt; props.name)<br>&lt;/script&gt;<br>&lt;style scoped&gt;<br>.wrapper {<br>  display: flex;<br>  flex-direction: column;<br>  margin-bottom: 10px;<br>  gap: 3px;<br>}<br>.error_message {<br>  color: red;<br>}<br>.field_error {<br>  border: 1px solid red !important;<br>}<br>.input {<br>  width: 100%;<br>  height: 30px;<br>  border-radius: 5px;<br>  padding: 10px;<br>  border: 0.5px solid gray;<br>}<br>.input:focus {<br>  outline: none;<br>}<br>.valid {<br>  border: 1px solid green !important;<br>}<br>label {<br>  font-size: 14px;<br>  font-weight: 600;<br>}<br>&lt;/style&gt;</pre><p>In this component, we use VeeValidate’s useField to handle field validation. We also define a few props to make the component flexible.</p><h4>Setting Up Form Validation with VeeValidate and Yup</h4><blockquote>File name: FormComponent.vue</blockquote><pre>&lt;template&gt;<br>  &lt;div class=&quot;container&quot;&gt;<br>    &lt;Form ref=&quot;form&quot; :validation-schema=&quot;schema&quot; @submit=&quot;submit&quot; :initial-values=&quot;formData&quot;&gt;<br>      &lt;custom-input placeholder=&quot;Full Name&quot; label=&quot;Full Name&quot; name=&quot;name&quot; type=&quot;text&quot; /&gt;<br>      &lt;custom-input placeholder=&quot;email&quot; label=&quot;Email&quot; name=&quot;email&quot; type=&quot;email&quot; /&gt;<br>      &lt;custom-input placeholder=&quot;Job Type&quot; label=&quot;Job Type&quot; name=&quot;job_type&quot; /&gt;<br>      &lt;custom-input placeholder=&quot;Customer Name&quot; label=&quot;Customer Name&quot; name=&quot;customer_name&quot; /&gt;<br><br>      &lt;div class=&quot;button-wrapper&quot;&gt;<br>        &lt;button class=&quot;btn btn-success&quot; type=&quot;submit&quot;&gt;submit&lt;/button&gt;<br>        &lt;button @click=&quot;reset&quot; class=&quot;btn btn-danger&quot; type=&quot;button&quot;&gt;Reset&lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/Form&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script setup&gt;<br>import { Form } from &#39;vee-validate&#39;<br>import { ref } from &#39;vue&#39;<br>import * as yup from &#39;yup&#39;<br>import CustomInput from &#39;@/components/CustomInput.vue&#39;<br><br>const form = ref(null)<br>const schema = yup.object().shape({<br>  name: yup.string().required().min(6),<br>  email: yup.string().email().required(),<br>  job_type: yup.string().required(&#39;Job Type field is required&#39;),<br>  customer_name: yup.string().required(&#39;Customer Name field is required&#39;)<br>})<br><br>const formData = ref({<br>  name: &#39;&#39;,<br>  email: &#39;&#39;,<br>  job_type: &#39;&#39;,<br>  customer_name: &#39;&#39;<br>})<br><br>const submit = (values) =&gt; {<br>  // implement your logic here<br>  console.log(values)<br>}<br>const reset = () =&gt; {<br>  form.value.resetForm()<br>}<br>&lt;/script&gt;<br>&lt;style scoped&gt;<br>.container {<br>  padding: 20px;<br>  width: 300px;<br>}<br><br>.btn {<br>  height: 35px;<br>  padding: 0px 20px;<br>  background-color: gray;<br>  color: white;<br>  border-radius: 5px;<br>}<br>.button-wrapper {<br>  display: flex;<br>  gap: 10px;<br>}<br>.btn-success {<br>  background-color: rgb(64, 181, 64);<br>}<br>.btn-danger {<br>  background-color: rgb(186, 17, 17);<br>}<br>&lt;/style&gt;</pre><ol><li>Form Setup: We use the Form component from VeeValidate to manage the form state and validation. The validation-schema prop links the form to our Yup schema.</li></ol><pre>const schema = yup.object().shape({<br>  name: yup.string().required().min(6),<br>  email: yup.string().email().required(),<br>  job_type: yup.string().required(&#39;Job Type field is required&#39;),<br>  customer_name: yup.string().required(&#39;Customer Name field is required&#39;)<br>})</pre><p>2. Initial Values: The initial-values prop in the Form component is used to set the initial state of the form fields. This prop is particularly useful for pre-filling the form with data, making it easier to edit existing records or initialize the form with default values. In this example, we define the initial values in the formData object, which is then passed to the Form component.</p><pre>const formData = ref({<br>  name: &#39;&#39;,<br>  email: &#39;&#39;,<br>  job_type: &#39;&#39;,<br>  customer_name: &#39;&#39;<br>})</pre><h4>Conclusion</h4><p>In this article, we’ve demonstrated how to implement form validation in Vue 3 using the Composition API, VeeValidate, and Yup. We’ve also shown how to create a custom input component that can be reused across your application. By following these steps, you can ensure your forms are robust and user-friendly.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fad601221ac6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>