<?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[tarfin - Medium]]></title>
        <description><![CDATA[Tarfin Technology Blog - Medium]]></description>
        <link>https://medium.com/tarfin?source=rss----1ce425a134e4---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>tarfin - Medium</title>
            <link>https://medium.com/tarfin?source=rss----1ce425a134e4---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 06:42:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/tarfin" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Financial Precision in Agriculture Fintech]]></title>
            <link>https://medium.com/tarfin/financial-precision-in-agriculture-fintech-7e65f659f717?source=rss----1ce425a134e4---4</link>
            <guid isPermaLink="false">https://medium.com/p/7e65f659f717</guid>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[financial-engineering]]></category>
            <category><![CDATA[decimalprecision]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Emre Deligöz]]></dc:creator>
            <pubDate>Wed, 28 May 2025 22:41:47 GMT</pubDate>
            <atom:updated>2025-05-29T21:31:04.452Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzEhYd6wCcJI5BbGsQYRgw.png" /></figure><h3>Financial Precision in Agriculture Fintech: Our Journey from 2 to 16 Decimal Places</h3><h3>Introduction</h3><p>At <a href="https://www.tarfin.com/">Tarfin</a>, Europe’s leading fintech platform for farmer agri-input financing, thousands of farmers have chosen us to purchase their seeds, fertilizers, feed and equipment with flexible payment terms. Founded in 2017 in Turkey, we help farmers across 75+ cities by letting them compare prices from 1200+ retailers and purchase agri-inputs without tying up their cash. Since 2021, we’ve expanded to Romania, bringing the same farmer-friendly financing model to help small and medium-sized farmers access agricultural inputs without guarantees or hidden costs</p><p>When we started building our system, we followed the best practices known at the time: storing monetary values as integers in the database to avoid floating-point rounding issues. However, as our business grew and became more sophisticated, we discovered that even this approach wasn’t sufficient. This article shares our journey of migrating from 2 decimal precision to a DECIMAL(29,16) structure in our database - that&#39;s 13 digits before the decimal point and 16 after.</p><h3>The Foundation: Brick/Money Library</h3><p>After experiencing the limitations of integer storage, we adopted the <a href="https://github.com/brick/money">Brick/Money</a> library for all monetary operations in our Laravel application:</p><pre>use Brick\Math\RoundingMode;<br>use Brick\Money\Money;<br>use Brick\Money\Context\CustomContext;<br><br>// Before: 2 decimal precision<br>$context2 = new CustomContext(2);<br>$price = Money::of(999.99, &quot;USD&quot;, $context2);<br>$commission = $price-&gt;multipliedBy(&quot;0.025&quot;, RoundingMode::HALF_UP); // 25 USD<br><br>// After: 16 decimal precision<br>$context16 = new CustomContext(16);<br>$price = Money::of(&quot;999.9999999999999&quot;, &quot;USD&quot;, $context16);<br>$commission = $price-&gt;multipliedBy(&quot;0.025&quot;, RoundingMode::HALF_UP); // 24.9999999999999975 USD</pre><h3>Our Starting Point: Integer Storage</h3><p>When we started building Tarfin, we knew about the dangers of floating-point arithmetic. The classic example every developer learns:</p><pre>$a = 0.1;<br>$b = 0.2;<br>$sum = $a + $b;<br><br>var_dump($sum === 0.3); // false!<br>printf(&quot;%.17f&quot;, $sum);  // 0.30000000000000004</pre><p>This happens because computers store floating-point numbers in binary (base 2), and many decimal fractions cannot be represented exactly in binary. Just like 1/3 cannot be precisely represented in decimal (0.333…), 0.1 cannot be precisely represented in binary.</p><p>That’s why we followed the best practice of storing monetary values as integers:</p><pre>// Instead of storing 100.50 USD as float<br>$price = 100.50; // Dangerous!<br><br>// We stored it as integer cents<br>$priceInCents = 10050; // Safe from floating-point errors</pre><p>The integer storage approach had several advantages:</p><h4>Exact Representation</h4><pre>// Float storage problems<br>$dbPrice = 19.99;<br>$quantity = 3;<br>$total = $dbPrice * $quantity; // 59.97... or is it?<br>printf(&quot;%.17f&quot;, $total); // 59.96999999999999886<br><br>// Integer storage (cents)<br>$dbPriceCents = 1999;<br>$quantity = 3;<br>$totalCents = $dbPriceCents * $quantity; // Exactly 5997<br>$totalUSD = $totalCents / 100; // 59.97</pre><h4>Consistent Database Operations</h4><pre>-- Float columns can have comparison issues<br>SELECT *<br>FROM orders<br>WHERE total = 59.97;<br>-- Might miss rows!<br><br>-- Integer columns are reliable<br>SELECT *<br>FROM orders<br>WHERE total_cents = 5997; -- Always works</pre><h4>No Accumulating Errors</h4><pre>// Float accumulation problem<br>$balance = 0.0;<br>for ($i = 0; $i &lt; 10000; $i++) {<br>    $balance += 0.01;<br>}<br>echo $balance; // 100.00000000001 (should be 100.00) <br>               // Note: exact error may vary by system/PHP version<br><br>// Integer accumulation is perfect<br>$balanceCents = 0;<br>for ($i = 0; $i &lt; 10000; $i++) {<br>    $balanceCents += 1;<br>}<br>echo $balanceCents / 100; // Exactly 100.00</pre><p>This integer approach worked well for amounts with 2 decimal places, but our business requirements soon exceeded these limitations.</p><h3>Why 2 Decimal Places Weren’t Enough</h3><h4>Income Protected Sales (IPS)</h4><p>Our Income Protected Sales (IPS) model — what we call “Gelir Korumalı Satış” in Turkish — is essentially a commodity price hedging mechanism for farmers. In this payment system, farmers can choose to pay based on the average commodity prices at their selected payment date, rather than the purchase date. This protects them from price volatility in agricultural markets.</p><p>For example, a farmer buying fertilizer in March can choose to pay in October based on October’s wheat prices. If wheat prices rise, they pay less; if prices fall, they’re protected by minimum price guarantees. This hedging mechanism requires extreme precision in calculations:</p><pre>// Example: 1000 USD sale equals 100kg of wheat<br>$cashPrice = &#39;1000.00&#39;;<br>$wheatAmount = &#39;100.1234567890123456&#39;; // kg<br>$wheatPrice = &#39;9.876543210987654321&#39;; // USD/kg<br><br>// With 2 decimals:<br>$result = round(100.12 * 9.88, 2); // 989.19 USD<br><br>// Actual value:<br>$result = &#39;989.1851851851851851...&#39;; // Significant difference!</pre><h4>VAT Calculations on Small Unit Price Products</h4><p>Seeds and similar agricultural inputs often have very small unit prices but are purchased in large quantities. This is where VAT (KDV in Turkish) calculation precision becomes critical:</p><pre>// Example: Seed with small unit price<br>$unitPrice = &#39;0.05&#39;; // 0.05 USD per seed<br>$quantity = 100000; // Farmer buys 100,000 seeds<br>$vatRate = 8; // 8% VAT<br><br>// With 2 decimal precision:<br>$unitPriceWithoutVat = round(0.05 / 1.08, 2); // 0.05 USD (wrong!)<br>$vatAmount = 0.00; // No VAT calculated!<br><br>// With 16 decimal precision:<br>$unitPriceWithoutVat = &#39;0.0462962962962963&#39;; // Correct<br>$vatAmount = &#39;0.0037037037037037&#39;; // Correct VAT<br><br>// For 100,000 seeds:<br>// 2 decimals: 0 USD VAT loss<br>// 16 decimals: 370.37 USD VAT correctly calculated</pre><p>When farmers purchase tens or hundreds of thousands of these small-unit items, rounding errors compound into significant amounts.</p><h3>Float vs String: The IEEE-754 Problem</h3><h4>What is IEEE-754?</h4><p>IEEE-754 is the standard for floating-point arithmetic used by virtually all modern computers. It represents numbers in binary (base 2) using three components:</p><ul><li><strong>Sign bit</strong>: Positive or negative</li><li><strong>Exponent</strong>: The magnitude of the number</li><li><strong>Mantissa (fraction)</strong>: The precision bits</li></ul><p>The problem is that many decimal fractions cannot be exactly represented in binary. Just as 1/3 becomes 0.333… ( infinite) in decimal, numbers like 0.1 become infinite in binary:</p><pre>0.1 in decimal = 0.00011001100110011... in binary (repeating forever)</pre><p>Since computers have finite memory, they must truncate this infinite representation, leading to rounding errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iplJKkfNuOlYixUz9g3BHA.png" /><figcaption>IEEE-754 Double Precision: Why 0.1 Cannot Be Exactly Represented</figcaption></figure><h4>The Mental Shift: From Float to String</h4><p>Moving from writing $amount = 1234.567 to $amount = &#39;999999.9999999999999999&#39; requires a fundamental mental shift for developers. It feels unnatural at first to treat numbers as strings, but this becomes inevitable when working with high-precision financial calculations - these precise decimal values simply cannot fit within the IEEE-754 standard without loss of precision.</p><h4>Real Examples from Our System</h4><p>Here’s something that surprised us: Laravel returns DECIMAL database values as strings, not floats. At first, this seemed odd — why would a numeric database type come back as a string? The answer reveals a deeper truth about precision.</p><p>PDO (PHP’s database layer) returns DECIMAL values as strings because PHP’s float type cannot accurately represent many decimal values. By returning strings, it preserves the exact precision stored in your database. The danger comes when developers, not understanding this protection, convert these strings to floats:</p><pre>use Brick\Money\Context\CustomContext;<br>use Brick\Money\Money;<br><br>$context = new CustomContext(16);<br><br>// PDO correctly returns DECIMAL as string to preserve precision<br>$dbAmount = &quot;999999.9999999999999999&quot;; // From DECIMAL(29,16) column<br><br>// String preserves exact value<br>$moneyStr = Money::of($dbAmount, &quot;USD&quot;, $context);<br>// Money amount: 999999.9999999999999999<br><br>// Developer &quot;helps&quot; by converting to float - DESTROYS precision!<br>$moneyFloat = Money::of((float) $dbAmount, &quot;USD&quot;, $context);<br>// Money amount: 1000000<br><br>// That&#39;s a 0.0000000000000001 USD difference that became 1 cent!</pre><p>The real danger comes from compounding errors in chained operations:</p><pre>// Chained operations with 16 decimal precision<br>$dbPrice = &#39;99999.1234567890123456&#39;;<br>$dbDiscount = &#39;0.1234567890123456&#39;;    // ~12.35% discount<br>$dbTax = &#39;0.2000000000000001&#39;;         // 20% VAT<br>$dbCommission = &#39;0.0123456789012345&#39;;   // Platform commission<br><br>// String approach: preserves all precision<br>// Float approach: compounds errors at each step<br>// Difference after 4 operations: 0.0000000006 USD<br><br>// Imagine processing thousands of transactions daily!</pre><h3>Performance Considerations</h3><p>You might worry about performance when using strings instead of floats. In our experience:</p><ul><li>The performance difference is negligible for most operations</li><li>The accuracy gained far outweighs any minimal performance cost</li><li>Database indexes work perfectly with DECIMAL(29,16) columns</li><li>Modern databases are optimized for decimal arithmetic</li></ul><p>However, there are trade-offs to consider:</p><ul><li><strong>Storage</strong>: Higher precision means more storage space. DECIMAL(29,16) uses more bytes than DECIMAL(10,2)</li><li><strong>Bulk Operations</strong>: When processing hundreds or thousands of calculations, string-based arithmetic is slower than native float operations</li><li><strong>The Right Balance</strong>: DECIMAL(29,16) was our sweet spot, but your application might need different precision based on your specific requirements</li></ul><p>The Brick/Money library mitigates performance impacts by using optimized arbitrary-precision arithmetic libraries like BCMath or GMP under the hood. These extensions are specifically designed for high-precision calculations and offer the best balance between accuracy and performance for financial applications.</p><h3>Laravel Implementation Best Practices</h3><h4>Model Casting</h4><p>Our journey with Laravel model casting evolved through several stages, following our database evolution:</p><pre>// Stage 0: INTEGER storage (cents) 💰<br>// Database: amount BIGINT (stored as cents)<br>protected $casts = [<br>    &#39;amount&#39; =&gt; &#39;integer&#39;,  // 10050 cents = 100.50 USD<br>];</pre><p>When we started, we stored monetary values as integers in cents. This worked well for avoiding floating-point issues, but limited us to 2 decimal precision.</p><p>After migrating to DECIMAL storage, we discovered something crucial: MySQL returns DECIMAL values as strings to PHP, while FLOAT/DOUBLE columns return as numbers. This happens because DECIMAL values can have precision that exceeds PHP’s float capacity (~15 significant digits).</p><pre>// Stage 1: WRONG - Don&#39;t cast DECIMAL to float! ❌<br>protected $casts = [<br>    &#39;amount&#39; =&gt; &#39;float&#39;,  // This destroys precision!<br>];<br>// Database value: &#39;999.9999999999999999&#39;<br>// After float cast: 1000.0</pre><p>We never actually implemented Stage 1 in production, but it’s a common mistake developers make when transitioning from integer to decimal storage.</p><pre>// Stage 2: BETTER - Preserve string from database ✅<br>protected $casts = [<br>    &#39;amount&#39; =&gt; &#39;string&#39;,  // Keeps &#39;999.9999999999999999&#39; intact<br>];</pre><p>This was our first working solution with DECIMAL columns. By keeping values as strings, we preserved all precision from the database. However, we still had to manually convert to Money objects everywhere.</p><pre>// Stage 3: GOOD - Custom Money cast with 2 decimal precision ✅ ✅<br>protected $casts = [<br>    &#39;amount&#39; =&gt; MoneyCast::class . &#39;:2&#39;,  // Auto-converts to Money object<br>];</pre><p>Creating a custom cast was a game-changer. Our MoneyCast automatically handled the conversion between DECIMAL database columns and Money objects.</p><pre>// Stage 4: BEST - Custom Money cast with 16 decimal precision ✅✅✅<br>protected $casts = [<br>    &#39;amount&#39; =&gt; MoneyCast::class . &#39;:16&#39;,  // Full precision Money objects<br>];<br><br>// Full precision maintained throughout the stack<br>$money = $model-&gt;amount; // Money object with 16 decimal precision<br>$preciseCalculation = $money-&gt;multipliedBy(&#39;1.0000000000000001&#39;);</pre><p>As we discovered edge cases with seeds, VAT calculations, and Income Protected Sales, we upgraded to 16 decimal precision. This custom cast automatically handles the conversion between our DECIMAL(29,16) database column and Money objects, ensuring precision is maintained throughout the application lifecycle.</p><h4>Database Migration</h4><p>When we decided to move from integer to DECIMAL(29,16), the migration process taught us valuable lessons:</p><pre>Schema::table(&#39;transactions&#39;, function (Blueprint $table) {<br>    // OLD: Stored as unsigned big integer (minor units)<br>    $table-&gt;unsignedBigInteger(&#39;amount&#39;); // Stored in cents<br>    <br>    // NEW: 13 integer digits + 16 decimal places = 29 total precision<br>    $table-&gt;decimal(&#39;amount&#39;, 29, 16);<br>});</pre><p>The actual migration required careful data conversion:</p><pre>public function up()<br>{<br>    // Step 1: Add temporary decimal column<br>    Schema::table(&#39;transactions&#39;, function (Blueprint $table) {<br>        $table-&gt;decimal(&#39;amount_decimal&#39;, 29, 16)-&gt;nullable();<br>    });<br><br>    // Step 2: Convert cents to dollars (divide by 100!)<br>    DB::statement(&#39;UPDATE transactions SET amount_decimal = amount / 100&#39;);<br><br>    // Step 3: Swap columns<br>    Schema::table(&#39;transactions&#39;, function (Blueprint $table) {<br>        $table-&gt;dropColumn(&#39;amount&#39;);<br>        $table-&gt;renameColumn(&#39;amount_decimal&#39;, &#39;amount&#39;);<br>    });<br>}</pre><h4>Database-Level Precision Verification</h4><p>When we chose DECIMAL(29,16), we naturally expected MySQL to handle the precision correctly — after all, that’s the whole point of the DECIMAL type. But given the critical nature of financial calculations, we decided to verify this assumption with comprehensive tests.</p><p>Our curiosity paid off with reassuring results:</p><pre>-- Test: Can MySQL accurately sum 10 tiny values?<br>-- 10 x 0.0000000000000001 should equal exactly 0.0000000000000010<br>SELECT SUM(amount) = 0.0000000000000010 as is_exact<br>FROM precision_test<br>WHERE amount = 0.0000000000000001;<br>-- Result: 1 (TRUE) ✓<br><br>-- Test: Can MySQL detect differences at the 16th decimal?<br>SELECT amount,<br>       amount = 100.0000000000000000 as equals_100<br>FROM precision_test<br>WHERE amount IN (100.0000000000000000, 100.0000000000000001);<br>-- Results show it correctly distinguishes between the values ✓</pre><p>These tests confirmed what we hoped: MySQL’s DECIMAL implementation is rock-solid. Aggregate functions preserve all decimal places, comparisons work at full precision, and there are no accumulation errors. This means database-level calculations (when needed for performance) won’t compromise precision.</p><p>However, this doesn’t change our golden rule: always pass DECIMAL values as strings to PHP and use Money objects for application-level calculations. The database handles storage and basic operations perfectly, but complex business logic belongs in the application layer with proper money handling libraries.</p><h4>Money Service Integration</h4><pre>use Brick\Money\Context\CustomContext;<br>use Brick\Money\Money;<br><br>// Context with 16 decimal precision<br>$context = new CustomContext(16);<br><br>// With DECIMAL(29,16), we can store:<br>// Max: 9,999,999,999,999.9999999999999999 USD (13 digits before, 16 after)<br>// This is well within safe number ranges for both PHP and JavaScript<br><br>// Always pass strings to Money::of()<br>$money = Money::of($dbAmount, &quot;USD&quot;, $context); // Precision preserved<br><br>// DECIMAL(29,16) handles large amounts perfectly<br>$largeAmount = &quot;9999999999999.9999999999999999&quot;; // Max for DECIMAL(29,16)<br>$money = Money::of($largeAmount, &quot;USD&quot;, $context); // Works perfectly</pre><h3>Common Pitfalls When Working with High Precision</h3><p>After implementing DECIMAL(29,16) and proper model casting, we discovered several non-obvious pitfalls in production:</p><h4>External Data Sources</h4><p>The biggest challenges come from data entering your system:</p><pre>// ❌ WRONG: Trusting external number formats<br>$csvImport = &quot;1.234,56&quot;; // European format from Excel<br>$apiResponse = [&quot;amount&quot; =&gt; 1.0e-16]; // Scientific notation<br><br>// ✅ CORRECT: Normalize before processing<br>$normalized = str_replace(&quot;,&quot;, &quot;.&quot;, str_replace(&quot;.&quot;, &quot;&quot;, $csvImport)); // Remove thousands separator first<br>$apiAmount = sprintf(&quot;%.16f&quot;, $apiResponse[&quot;amount&quot;]); // Convert scientific to decimal</pre><p>Money library will throw NumberFormatException for invalid formats, which is good - but it means you need robust input validation in your data pipelines.</p><h4>JSON Encoding Concerns</h4><p>When sending monetary values through APIs:</p><pre>use Brick\Money\Context\CustomContext;<br>use Brick\Money\Money;<br><br>$context = new CustomContext(16);<br><br>// ❌ RISKY: Direct JSON encoding might use scientific notation<br>$data = [&quot;amount&quot; =&gt; 0.0000000000000001];<br>echo json_encode($data); // {&quot;amount&quot;:1.0e-16} - Precision lost!<br><br>// ✅ CORRECT: Always use strings<br>$money = Money::of(&quot;0.0000000000000001&quot;, &quot;USD&quot;, $context);<br>$data = [&quot;amount&quot; =&gt; (string) $money-&gt;getAmount()]; // Cast to string<br>echo json_encode($data); // {&quot;amount&quot;:&quot;0.0000000000000001&quot;}<br><br>// Also watch out for json_decode!<br>$json = &#39;{&quot;price&quot;: 0.0000000000000001}&#39;;<br>$decoded = json_decode($json, true); // $decoded[&#39;price&#39;] is float!<br>$decodedSafe = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);</pre><p>These real-world issues taught us that high precision requires vigilance not just in calculations, but throughout your entire data flow.</p><h3>Creative Solution: Automatic Discount Coupons for Rounding Differences</h3><p>While we were working on our migration from 2 to 16 decimal precision — a significant infrastructure change that would take months to complete — we needed an immediate solution for the rounding differences that were causing daily headaches for our accounting team. Every invoice with a rounding discrepancy meant manual reconciliation work, explanations to farmers, and additional burden on our finance department.</p><p>This led us to develop what we initially thought of as a temporary workaround but turned out to be an ingenious approach that solved multiple problems at once. Rather than rushing the precision migration and risking errors, we could take our time to do it right while immediately eliminating the accounting team’s reconciliation burden.</p><p>The core challenge remained: while we perform all calculations using RationalMoney with infinite precision, our database and financial systems could only store prices with 2 decimal places (0.01 USD minimum). This creates an inevitable precision loss at the very last step - when we must convert our perfectly calculated rational numbers into storable decimal values.</p><h4>The Mathematical Challenge</h4><p>Consider this scenario from our Income Protected Sales calculations:</p><pre>// Target total: 999.99 USD to be distributed across 3 items<br>// Item ratios: 40%, 35%, 25%<br><br>// Perfect rational calculation:<br>Item 1: 399.996  USD → rounds to 400.00 USD<br>Item 2: 349.9965 USD → rounds to 350.00 USD  <br>Item 3: 249.9975 USD → rounds to 250.00 USD<br><br>// Total after rounding: 1000.00 USD (0.01 USD over!)</pre><p>Even though we maintain perfect precision throughout all calculations using RationalMoney, the final conversion to 2-decimal storage creates a 0.01 USD discrepancy. Across thousands of transactions, these penny differences could accumulate into significant amounts.</p><h4>Our Intelligent Solution</h4><p>Rather than accepting this precision loss or attempting to “fudge” the numbers, we developed an automated system that maintains both mathematical accuracy and accounting integrity. This solution immediately freed our accounting team from manual reconciliation work while we continued our careful migration to 16 decimal precision:</p><pre>public function handleRoundingDifference(<br>    IPSPriceCalculationContext $context,<br>    int $allocatedTotal,<br>    int $targetTotal<br>): void {<br>    $difference = $allocatedTotal - $targetTotal;<br>    $threshold = config(&#39;tarfin.application.max_uncorrected_rounding_difference&#39;);<br><br>    if ($difference &gt; $threshold) {<br>        // Create automatic coupon for the exact difference<br>        $coupon = Coupon::create([<br>            &#39;code&#39; =&gt; &#39;ROUND-&#39;.Str::random(8),<br>            &#39;description&#39; =&gt; &#39;Rounding Difference - Automatically created&#39;,<br>            &#39;redemption_limit&#39; =&gt; 1,<br>        ]);<br><br>        // Apply proportionally to maintain item ratios<br>        $this-&gt;distributeCouponProportionally($coupon, $order, $difference);<br>    }<br>}</pre><h4>How It Preserves Precision</h4><p>The key insight is that we perform all calculations at the RationalMoney level - with infinite precision - and only encounter rounding when converting to database storage:</p><pre>private function calculateItemPrices(OrderItem $item, Money $allocatedAmount, RationalMoney $minimumUnitPrice): array<br>{<br>    // Work with rational numbers for perfect precision<br>    $unitWithKdv = $allocatedAmount-&gt;toRational()-&gt;dividedBy($item-&gt;quantity);<br>    <br>    // All VAT calculations happen in rational space<br>    $prices = $this-&gt;calculatePriceComponents($unitWithKdv, $item-&gt;kdv);<br>    <br>    // Only at the very end do we convert to 2-decimal Money<br>    return [<br>        &#39;unit_w_kdv&#39; =&gt; $unitWithKdv,  // Still RationalMoney<br>        &#39;total_w_kdv_minor&#39; =&gt; $totalWithKdv-&gt;to(new CustomContext(2), RoundingMode::HALF_UP)<br>                                            -&gt;getMinorAmount()-&gt;toInt()<br>    ];<br>}</pre><p>This approach ensures:</p><ol><li><strong>Perfect calculation accuracy</strong>: All intermediate calculations use RationalMoney</li><li><strong>Transparent correction</strong>: Any rounding difference is explicitly recorded as a discount</li><li><strong>Proportional distribution</strong>: The discount is distributed maintaining the original price ratios</li><li><strong>Complete auditability</strong>: Every penny is accounted for in the system</li></ol><h4>Real-World Example</h4><p>From our test suite, here’s how it works in practice:</p><pre>// Order with calculated forward price: 10,000.00 USD<br>// After allocation and rounding: 10,001.00 USD<br>// Difference: 1.00 USD<br><br>// System automatically:<br>// 1. Creates coupon ROUND-X8K2M9P1 for 1.00 USD<br>// 2. Distributes proportionally:<br>//    - Item 1 (60% of order): 0.60 USD discount<br>//    - Item 2 (40% of order): 0.40 USD discount<br>// 3. Final totals match exactly: 10,000.00 USD</pre><h4>Handling Edge Cases with Minimum Constraints</h4><p>The solution becomes even more sophisticated when dealing with minimum price constraints. Each price component (unit price, VAT amount) must be at least 0.01 USD:</p><pre>private function ensureMinimumPrices(array $prices, int $kdv, RationalMoney $minimumUnitPrice): array<br>{<br>    // Complex logic to ensure all components meet minimums<br>    // while maintaining mathematical consistency:<br>    // Unit Price with VAT = Unit Price without VAT + VAT Amount<br>    <br>    if ($prices[&#39;unit_kdv_amount&#39;]-&gt;isLessThan($minimumUnitPrice)) {<br>        // Recalculate from KDV amount to ensure minimum<br>        return $this-&gt;adjustFromKdvAmount($minimumUnitPrice, $kdv);<br>    }<br>    // ... other adjustments<br>}</pre><p>This ensures that even when dealing with very small amounts or high-volume transactions, every component remains valid while the total remains accurate.</p><h4>The State Machine Integration</h4><p>This entire process is orchestrated through our Event Machine, ensuring that rounding corrections only happen after all calculations are complete and validated:</p><pre>&#39;calculate&#39; =&gt; [<br>    &#39;on&#39; =&gt; [<br>        &#39;@always&#39; =&gt; [<br>            &#39;actions&#39; =&gt; [<br>                CalculateNewForwardPriceAction::class,      // RationalMoney calculations<br>                UpdateOrderItemsAction::class,              // Includes rounding handling<br>            ],<br>        ],<br>    ],<br>],</pre><p>By treating rounding differences as explicit discounts rather than hidden adjustments, we’ve created a system that is both mathematically precise and completely transparent. This approach has eliminated reconciliation issues while maintaining the trust of thousands of farmers who rely on our platform for fair and accurate pricing.</p><p>What started as a clever workaround during our precision migration became a permanent feature of our system. Even after completing the migration to DECIMAL(29,16), we kept this automatic coupon system because it elegantly handles the final rounding step when converting from our high-precision calculations to the 2-decimal invoices that integrate with external accounting systems. It transformed a daily accounting burden into a fully automated, transparent process that requires zero manual intervention.</p><h3>State Machine Implementation with Event Machine</h3><p>The entire IPS price calculation process is orchestrated using our open-source <a href="https://github.com/tarfin-labs/event-machine">Event Machine</a> package, which provides a robust state machine implementation for Laravel:</p><pre>class IPSPriceCalculationMachine extends Machine<br>{<br>    public static function definition(): ?MachineDefinition<br>    {<br>        return MachineDefinition::define(<br>            config: [<br>                &#39;id&#39; =&gt; &#39;ips_price_calculation&#39;,<br>                &#39;initial&#39; =&gt; &#39;idle&#39;,<br>                &#39;states&#39; =&gt; [<br>                    &#39;idle&#39; =&gt; [<br>                        &#39;on&#39; =&gt; [<br>                            &#39;START&#39; =&gt; [<br>                                &#39;target&#39; =&gt; &#39;calculate&#39;,<br>                                &#39;guards&#39; =&gt; [<br>                                    OrderIsNotDemoGuard::class,<br>                                    OrderIsCompletedGuard::class,<br>                                    OrderIsUnpaidGuard::class,<br>                                ],<br>                            ],<br>                        ],<br>                    ],<br>                    &#39;calculate&#39; =&gt; [<br>                        &#39;on&#39; =&gt; [<br>                            &#39;@always&#39; =&gt; [<br>                                &#39;target&#39; =&gt; &#39;done&#39;,<br>                                &#39;actions&#39; =&gt; [<br>                                    CalculateAndCacheMonthlyCropPriceAverageAction::class,<br>                                    CalculateNewForwardPriceAction::class,<br>                                    UpdateOrderItemsAction::class,<br>                                ],<br>                            ],<br>                        ],<br>                    ],<br>                ],<br>            ],<br>        );<br>    }<br>}</pre><p>This state machine ensures that price calculations only happen when all conditions are met and maintains a clear audit trail of the process.</p><h3>Real-World Testing: Mixed VAT Rates</h3><p>Our test suite includes complex scenarios like handling multiple VAT rates simultaneously:</p><pre>#[Test]<br>public function it_allocates_prices_proportionally_with_mixed_vat_rates(): void<br>{<br>    // Products with 0%, 10%, and 20% VAT rates<br>    // Updating total from 10,000 USD to 12,000 USD<br>    // Each product gets proportional share<br>    // VAT calculations are preserved<br>    // Minimum price constraints are enforced<br>}</pre><h3>Testing High-Precision Financial Calculations</h3><p>Testing financial calculations with 16 decimal precision requires special attention. Here’s how we approach it:</p><h4>String Comparison for Exact Matching</h4><pre>#[Test]<br>public function it_calculates_commission_with_full_precision()<br>{<br>    $amount = &#39;999999.9999999999999999&#39;;<br>    $rate = &#39;0.0000123456789012&#39;;<br>    <br>    $result = calculateCommission($amount, $rate);<br>    <br>    // Don&#39;t use floats for comparison!<br>    $this-&gt;assertEquals(<br>        &#39;12.3456789011999999&#39;,  // Expected as string<br>        (string) $result-&gt;getAmount()<br>    );<br>}</pre><h4>Testing Rounding Boundaries</h4><pre>#[Test]<br>public function it_handles_rounding_at_16th_decimal()<br>{<br>    $price = Money::of(&#39;99.9999999999999999&#39;, &#39;USD&#39;, new CustomContext(16));<br>    $quantity = &#39;1.0000000000000001&#39;;<br>    <br>    $total = $price-&gt;multipliedBy($quantity, RoundingMode::HALF_UP);<br>    <br>    // Test that rounding occurs correctly at the 16th decimal<br>    $this-&gt;assertEquals(<br>        &#39;100.0000000000000099&#39;,  // Correct result after rounding<br>        (string) $total-&gt;getAmount()<br>    );<br>}</pre><h4>Testing Edge Cases</h4><pre>#[Test]<br>public function it_handles_maximum_decimal_values()<br>{<br>    // Maximum value for DECIMAL(29,16)<br>    $maxValue = &#39;9999999999999.9999999999999999&#39;;<br>    <br>    $money = Money::of($maxValue, &#39;USD&#39;, new CustomContext(16));<br>    <br>    // Ensure no overflow or precision loss<br>    $this-&gt;assertEquals($maxValue, (string) $money-&gt;getAmount());<br>    <br>    // Test that adding would exceed DECIMAL(29,16) limits<br>    $result = $money-&gt;plus(Money::of(&#39;0.0000000000000001&#39;, &#39;USD&#39;, new CustomContext(16)));<br>    <br>    // Result exceeds database storage limits<br>    $this-&gt;assertEquals(<br>        &#39;10000000000000.0000000000000000&#39;,<br>        (string) $result-&gt;getAmount()<br>    );<br>    <br>    // This value cannot be stored in DECIMAL(29,16)<br>    // Database insertion would fail with:<br>    // &quot;Out of range value for column &#39;amount&#39;&quot;<br>}</pre><h3>Key Learnings and Recommendations</h3><ol><li><strong>Never use floats</strong>: IEEE-754 binary floating point is not suitable for financial calculations</li><li><strong>Use String/BigDecimal</strong>: Process without precision loss</li><li><strong>Store sufficient decimals</strong>: 2 decimals are insufficient for modern fintech</li><li><strong>Test edge cases</strong>: Always test with very large and very small numbers</li><li><strong>Watch for chained operations</strong>: Errors compound exponentially</li><li><strong>Define rounding strategy</strong>: Consider automatic correction mechanisms like ours</li><li><strong>Use state machines</strong>: Complex financial processes benefit from explicit state management</li><li><strong>DECIMAL(29,16) is powerful</strong>: Supports up to 9,999,999,999,999.9999999999999999 — more than enough for most financial applications</li></ol><h3>Conclusion</h3><p>In financial technology, we need to think not in terms of “cents” but in terms of “0.0000000000000001 cents”. Over millions of transactions, these tiny differences can compound into significant losses.</p><p>Moving to DECIMAL(29,16) precision - with 13 digits before and 16 after the decimal point - has eliminated rounding errors, enabled more sophisticated financial products, and given us the confidence that every cent is accounted for accurately. This precision allows us to handle amounts up to 9,999,999,999,999.9999999999999999 USD, which covers all our current and foreseeable future needs.</p><p><em>This article is based on the production implementation of Tarfin’s Income Protected Sales (IPS) model. Some of the code examples are from our actual codebase, demonstrating real-world fintech challenges and solutions.</em></p><p><em>The </em><a href="https://github.com/tarfin-labs/event-machine"><em>Event Machine</em></a><em> package mentioned in this article is open-source and available for use in your Laravel projects.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e65f659f717" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tarfin/financial-precision-in-agriculture-fintech-7e65f659f717">Financial Precision in Agriculture Fintech</a> was originally published in <a href="https://medium.com/tarfin">tarfin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Reserved Attribute Names in Laravel’s Eloquent ORM]]></title>
            <link>https://medium.com/tarfin/understanding-reserved-attribute-names-in-laravels-eloquent-orm-9a2844279158?source=rss----1ce425a134e4---4</link>
            <guid isPermaLink="false">https://medium.com/p/9a2844279158</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[reserved-attribute-names]]></category>
            <category><![CDATA[eloquent]]></category>
            <dc:creator><![CDATA[Turan Karatuğ]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 06:43:44 GMT</pubDate>
            <atom:updated>2023-07-25T06:43:43.958Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dmMld6FsqwBAWc45OLDVfQ.png" /></figure><p>Laravel’s Eloquent ORM is a powerful tool for interacting with databases in PHP. It provides a simple and expressive syntax to perform database operations, such as querying and manipulating records. When working with Eloquent, it’s important to be aware of reserved attribute names to avoid conflicts with column names in your database tables. In this blog post, we’ll explore the concept of reserved attribute names and discuss best practices to prevent potential issues.</p><h4>Understanding Reserved Attribute Names</h4><p>In Laravel’s Eloquent, each database table has a corresponding model that represents the table’s structure and data. By default, Eloquent assumes that the model’s properties (also known as attributes) directly map to the table’s columns. However, some attribute names are reserved and have special meanings within the Eloquent ORM.</p><p>The reserved attribute names in Eloquent are primarily related to model lifecycle events, relationships, and query scopes. These reserved names should not be used as column names in your database tables to avoid conflicts and unexpected behavior.</p><h4>1. Model Lifecycle Events</h4><p>Eloquent provides several lifecycle events, such as <strong>creating</strong>, <strong>updating</strong>, <strong>deleting</strong>, <strong>saving</strong>, and <strong>retrieving</strong>, that allow you to hook into specific moments during the model’s lifespan. When defining event listeners or methods for these events, you should avoid using attribute names that correspond to column names in your tables.</p><p>For example, if you have a column named “<strong><em>creating</em></strong>” in your table, using the attribute name “<strong><em>creating</em></strong>” for a model property would create ambiguity and may lead to unexpected results. Instead, choose descriptive attribute names that do not clash with these reserved event names.</p><h4>2. Relationships</h4><p>Eloquent offers a convenient way to define relationships between models, such as <strong>one-to-one</strong>, <strong>one-to-many</strong>, and <strong>many-to-many</strong> relationships. To define a relationship, you typically use methods on the model, which act as dynamic properties. It’s crucial to avoid using attribute names that conflict with these relationship methods.</p><p>For instance, if you have a column named “<strong><em>belongsTo</em></strong>” in your table, using “<strong><em>belongsTo</em></strong>” as an attribute name for a model property could cause conflicts when defining the actual relationship. Opt for more descriptive attribute names that clearly indicate the purpose of the property.</p><h4>3. Query Scopes</h4><p>Query scopes in Laravel allow you to encapsulate commonly used query constraints within your models. These scopes are defined as methods on the model and provide a convenient way to reuse complex queries. When defining query scopes, it’s essential to avoid using attribute names that overlap with reserved names used by Eloquent.</p><p>For example, if you have a column named “<strong><em>globalScope</em></strong>” in your table, using “<strong><em>globalScope</em></strong>” as an attribute name might cause conflicts with query scopes defined on the model. Instead, choose attribute names that accurately reflect the intended behavior of the property.</p><h4>Best Practices to Prevent Conflicts</h4><p>To prevent conflicts and unexpected behavior when working with reserved attribute names in Eloquent, consider the following best practices:</p><ol><li><strong>Use descriptive attribute names:</strong> Choose attribute names that clearly convey the purpose of the property and avoid generic terms that may clash with reserved names.</li><li><strong>Prefix or suffix attributes:</strong> Consider adding a consistent prefix or suffix to attribute names to differentiate them from reserved names. For example, prefixing relationship attributes with “<strong><em>related_</em></strong>” or suffixing event-related attributes with “<strong><em>_event</em></strong>” can help avoid conflicts.</li><li><strong>Check the Eloquent documentation:</strong> Laravel’s documentation provides a comprehensive list of reserved attribute names. Before naming your attributes, refer to the official documentation to ensure you avoid potential conflicts.</li></ol><h4>Real-World Example: Avoiding the “changes” Conflict</h4><p>Let’s consider a real-world example to highlight the importance of avoiding conflicts with reserved attribute names. Suppose you have a table named “<strong><em>users</em></strong>” with a column named “<strong><em>changes</em></strong>” that stores the number of changes made to a user’s profile. In your User model, you decide to name an attribute as “<strong><em>changes</em></strong>” to access and display this value.</p><p>However, “<strong><em>changes</em></strong>” is a reserved attribute name in Eloquent. When retrieving or updating the user model, you may encounter unexpected behavior or errors due to the conflict between the attribute name and the reserved name. To prevent this conflict, you should choose an alternative attribute name, such as “<strong><em>profileChanges</em></strong>” or “<strong><em>changeCount</em></strong>,” that accurately represents the purpose of the property without clashing with reserved names.</p><h4>Conclusion</h4><p>Understanding and avoiding reserved attribute names is crucial when working with Laravel’s Eloquent ORM. By following best practices and choosing descriptive attribute names, you can prevent conflicts with column names in your database tables and ensure smooth and predictable behavior in your application. Always consult the official Laravel documentation for an up-to-date list of reserved attribute names and stay mindful of potential naming conflicts in your Eloquent models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a2844279158" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tarfin/understanding-reserved-attribute-names-in-laravels-eloquent-orm-9a2844279158">Understanding Reserved Attribute Names in Laravel’s Eloquent ORM</a> was originally published in <a href="https://medium.com/tarfin">tarfin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code Refactoring in Action: Optimizing a Legacy List of Dates Method with Laravel and Carbon]]></title>
            <link>https://medium.com/tarfin/code-refactoring-in-action-optimizing-a-legacy-list-of-dates-method-with-laravel-and-carbon-691452d3470a?source=rss----1ce425a134e4---4</link>
            <guid isPermaLink="false">https://medium.com/p/691452d3470a</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Emre Deligöz]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 15:22:47 GMT</pubDate>
            <atom:updated>2023-07-04T15:42:36.843Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*wuqdJEPvszC6xusCIE-ZjA.png" /></figure><p><em>In the world of software development, better code is often synonymous with concise, efficient, and accurate code. Enter refactoring, the art of honing our code to improve its quality without changing its behavior. Today, let&#39;s explore this concept in a Laravel project, taking a deep dive into the details of the transformation.</em></p><h3>Setting the Stage</h3><p>Our story starts with an Eloquent <strong>Holiday</strong> model in a Laravel application. This model represents a holiday record in our application, consisting of four attributes:</p><ul><li><strong>name</strong> (the holiday&#39;s name)</li><li><strong>start_date</strong> (the date when the holiday begins)</li><li><strong>end_date</strong> (the date when the holiday concludes)</li><li>and <strong>is_public_holiday</strong> (a boolean flag indicating if the holiday is public or not).</li></ul><p>Among its methods, the <strong>Holiday</strong> model featured one called <strong>getAllHolidayDates()</strong>. This method was designed to fetch all holiday records and generate a unique list of holiday dates. The idea was simple yet essential: to have a go-to function that could provide us with all the distinct holiday dates we would need.</p><p>While the function did its job, we began to notice areas for improvement. As we analyzed the code, we found that it could benefit from increased efficiency and readability. We also discovered an accuracy issue that needed to be addressed.</p><p>And thus began our journey of code refactoring...</p><h3>The Original getAllHolidayDates() Function</h3><p>The original implementation was built using PHP&#39;s <strong>DateTime</strong>, <strong>DatePeriod</strong>, and <strong>DateInterval</strong> classes. However, we encountered an issue when the <strong>start_date</strong> and <strong>end_date</strong> of a holiday were identical. In such cases, the function incorrectly omitted these dates from the returned array. Coupled with unnecessary complexity from nested conditionals and loops, we realized we had a perfect candidate for refactoring.</p><pre>/**<br> * @throws \\Exception<br> *<br> * @return \\DatePeriod[]<br> */<br>public static function getAllHolidayDates(bool $onlyPublic = false): array<br>{<br>    $allHolidays = $onlyPublic<br>        ? self::where(&#39;is_public_holiday&#39;, 1)-&gt;get()<br>        : self::all();<br><br>    $list = [];<br>    foreach ($allHolidays as $holiday) {<br>        if ($holiday[&#39;start_date&#39;] == $holiday[&#39;end_date&#39;]) {<br>            $list[] = (new DateTime($holiday[&#39;start_date&#39;]))-&gt;format(&#39;Y-m-d&#39;);<br>        } else {<br>            $period = new DatePeriod(<br>                new DateTime($holiday[&#39;start_date&#39;]),<br>                new DateInterval(&#39;P1D&#39;),<br>                new DateTime($holiday[&#39;end_date&#39;])<br>            );<br>            foreach ($period as $date) {<br>                $list[] = $date-&gt;format(&#39;Y-m-d&#39;);<br>            }<br>        }<br>    }<br><br>    return $list;<br>}</pre><h3>The Journey of Refactoring</h3><h4>Becoming Selective: Focused Data Retrieval</h4><p>In the original implementation, we were fetching all the columns from our <strong>Holiday</strong> model, regardless of whether we needed them or not. This practice could be unnecessarily memory-intensive and inefficient, particularly as our data grows.</p><pre>public static function getAllHolidayDates(bool $onlyPublic = false): array<br>{<br>    return self::query()<br>        .select([&#39;id&#39;, &#39;start_date&#39;, &#39;end_date&#39;, &#39;is_public_holiday&#39;])<br>        ...</pre><p>In the refactored version, we&#39;ve become more selective with our data retrieval. We&#39;re now specifically asking for the <strong>id</strong>, <strong>start_date</strong>, <strong>end_date</strong>, and <strong>is_public_holiday</strong> columns. This tailored selection means we&#39;re only fetching the data we require for our operations, optimizing memory usage and improving the efficiency of our query.</p><p>It&#39;s a clear reminder that every bit counts in optimizing our code. So being mindful of what data we bring into our application can have a significant impact on our overall application performance.</p><h4>Streamlining Conditionals: The Power of Laravel&#39;s `when()` Method</h4><pre>...<br>  -&gt;when($onlyPublic, fn ($query) =&gt; $query-&gt;where(&#39;is_public_holiday&#39;, true))<br>  ...</pre><p>Next, we utilize Laravel&#39;s <strong>when()</strong> method, conditionally applying a <strong>where()</strong> clause only when <strong>$onlyPublic</strong> is <strong>true</strong>. This refines our query to fetch only public holidays when required, without the need for an explicit conditional statement. This change makes our data retrieval logic more streamlined and readable.</p><h4>Excluding Past Holidays: Enhancing Data Relevance</h4><pre>...<br>  -&gt;where(&#39;end_date&#39;, &#39;&gt;=&#39;, now()-&gt;startOfDay())<br>  -&gt;get()<br>  ...</pre><p>Adding to our efficient data retrieval strategy, we included a new where clause to the query. This clause ensures that we only fetch holidays that are either currently ongoing or will happen in the future. The logic is simple - if a holiday&#39;s <strong>end_date</strong> is today or any future date, we need that data; if it&#39;s in the past, we can disregard it.</p><p>This enhancement keeps our data relevant and can significantly reduce the load on our system as the data grows over time. It&#39;s another testament to the importance of being selective and thoughtful when fetching data, and how such mindful practices can enhance both our application&#39;s efficiency and accuracy.</p><h4>Date Range Generation: Harnessing Laravel and Carbon&#39;s Elegance</h4><pre>...<br>    -&gt;flatMap(fn ($holiday) =&gt; collect(CarbonPeriod::create(<br>        Carbon::parse($holiday[&#39;start_date&#39;]),<br>        Carbon::parse($holiday[&#39;end_date&#39;])<br>    ))-&gt;map-&gt;format(&#39;Y-m-d&#39;))<br>    ...</pre><p>Here, we create a date range for each holiday using Carbon&#39;s <strong>CarbonPeriod</strong> class. <strong>flatMap()</strong> flattens the multidimensional array into a single level, making it more manageable. We then format these dates into string format using <strong>map()</strong>, resulting in a cleaner and more readable way of generating our date list.</p><h4>Refining the Output: Leveraging Laravel&#39;s Collection Methods</h4><pre>...<br>  -&gt;unique()<br>  -&gt;sort()<br>  -&gt;values()<br>  -&gt;toArray();<br>}</pre><p>We chain <strong>unique()</strong>, <strong>sort()</strong>, and <strong>values()</strong> methods. <strong>unique()</strong> eliminates duplicate dates, <strong>sort()</strong> organizes the dates in ascending order, and <strong>values()</strong> re-indexes the array keys. We then convert the Collection back to an array for the return. This chaining ensures our returned array only contains unique, sorted dates, and it does so in a succinct, readable manner.</p><h4>Improving Documentation: The Significance of Updated DocBlocks</h4><p>Lastly, code is read by humans more often than machines, making documentation a crucial part of any software project. Initially, our <strong>getAllHolidayDates()</strong> method&#39;s DocBlock was scarce, providing little context about the method&#39;s behavior and purpose. During our refactoring process, we also aimed to improve this aspect. The updated DocBlock is now more informative, providing a clear, concise description of what the function does, its parameters, and return value.</p><pre>/**<br> * Retrieve all unique holiday dates.<br> *<br> * This method fetches all holiday records, generates a date range for each<br> * holiday, and returns a flattened array of unique date strings.<br> *<br> * @param bool $onlyPublic If true, only public holidays are returned.<br> *<br> * @return array An array of unique holiday date strings.<br> */<br>public static function getAllHolidayDates(bool $onlyPublic = false): array<br>{<br>...</pre><h3>The Finale</h3><p>Through our journey of refactoring, we transformed our function from a bug-prone, complex operation into an efficient, readable, and accurate tool that leverages the power of Laravel&#39;s Eloquent ORM and Carbon library. It&#39;s a testimony to how regular refactoring can optimize our codebase for maintainability, efficiency, and correctness.</p><p>In our case, using <strong>CarbonPeriod</strong> eliminated the bug where identical <strong>start_date</strong> and <strong>end_date</strong> were omitted. As a result, our function now accurately represents all holidays, regardless of their duration. Moreover, the use of Carbon, coupled with Laravel&#39;s collection methods, gave us a simpler and more intuitive way to deal with dates and arrays, enhancing our code&#39;s readability.</p><p>Additionally, with the judicious use of Laravel&#39;s <strong>query()</strong> and <strong>when()</strong>, we ensured that our database queries were only as complex as they needed to be. This aspect not only increases our code&#39;s efficiency by reducing unnecessary data retrieval but also streamlines our logic, making the code easier to understand and maintain.</p><p>The refactored function also demonstrates the power of method chaining in Laravel&#39;s Eloquent ORM and collections. Instead of several lines of separate instructions, we&#39;ve consolidated our actions into a single, coherent pipeline of operations. This technique significantly boosts our code&#39;s readability and elegance, and can even provide minor performance benefits.</p><p>Lastly, by focusing only on the necessary columns with the <strong>select()</strong> method, we reduce memory usage, making our function more scalable. Similarly, sorting and eliminating duplicates at the collection level, instead of relying on PHP array functions, can be more efficient with large data sets.</p><pre>/**<br> * Retrieve all unique holiday dates.<br> *<br> * This method fetches all holiday records, generates a date range for each<br> * holiday, and returns a flattened array of unique date strings.<br> *<br> * @param bool $onlyPublic If true, only public holidays are returned.<br> *<br> * @return array An array of unique holiday date strings.<br> */<br>public static function getAllHolidayDates(bool $onlyPublic = false): array<br>{<br>    return self::query()<br>        -&gt;select([&#39;id&#39;, &#39;start_date&#39;, &#39;end_date&#39;, &#39;is_public_holiday&#39;])<br>        -&gt;when($onlyPublic, fn ($query) =&gt; $query-&gt;where(&#39;is_public_holiday&#39;, true))<br>        -&gt;where(&#39;end_date&#39;, &#39;&gt;=&#39;, now()-&gt;startOfDay())<br>        -&gt;get()<br>        -&gt;flatMap(fn ($holiday) =&gt; collect(CarbonPeriod::create(<br>            Carbon::parse($holiday[&#39;start_date&#39;]),<br>            Carbon::parse($holiday[&#39;end_date&#39;])<br>        ))-&gt;map-&gt;format(&#39;Y-m-d&#39;))<br>        -&gt;unique()<br>        -&gt;sort()<br>        -&gt;values()<br>        -&gt;toArray();<br>}</pre><p>In conclusion, refactoring isn&#39;t just about changing code; it&#39;s about improving it. It&#39;s about making our code more efficient, more readable, more accurate, and ultimately, more enjoyable to work with. Whether you&#39;re a beginner or a seasoned developer, refactoring is a crucial skill in your toolkit. After all, good code is a journey, not a destination. So, keep refactoring, keep improving. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=691452d3470a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tarfin/code-refactoring-in-action-optimizing-a-legacy-list-of-dates-method-with-laravel-and-carbon-691452d3470a">Code Refactoring in Action: Optimizing a Legacy List of Dates Method with Laravel and Carbon</a> was originally published in <a href="https://medium.com/tarfin">tarfin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Validating `multipart/form-data` with Laravel Validation Rules with proper JSON data types]]></title>
            <link>https://medium.com/tarfin/validating-multipart-form-data-with-laravel-validation-rules-with-proper-json-data-types-ad3e40005a61?source=rss----1ce425a134e4---4</link>
            <guid isPermaLink="false">https://medium.com/p/ad3e40005a61</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[upload]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[validation-rule]]></category>
            <dc:creator><![CDATA[Emre Deligöz]]></dc:creator>
            <pubDate>Thu, 13 Jan 2022 06:47:55 GMT</pubDate>
            <atom:updated>2022-08-25T20:19:40.962Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LTc7xp6wKMh9xtAnubCuhg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@benofthenorth">Ben Griffiths</a> / <a href="https://unsplash.com/photos/4wxWBy8Jo1I">Unsplash</a></figcaption></figure><p>This article co-written by <a href="https://medium.com/@deligoez">Yunus Emre Deligöz</a>, <a href="https://medium.com/@oguzhan.karacabay">Oğuzhan Karacabay</a> and available in both <a href="https://medium.com/tarfin/validating-multipart-form-data-with-laravel-validation-rules-with-proper-json-data-types-ad3e40005a61">English</a> and <a href="https://medium.com/tarfin/laravelde-multipart-form-data-i%CC%87steklerini-do%C4%9Fru-json-veri-tipleri-ile-do%C4%9Frulama-888284bad42">Turkish</a>, co-published on my <a href="https://deligoz.me/articles/validating-multipart-form-data-with-laravel-validation-rules-with-proper-json-data-types/">blog</a>.</p><p>When you want both upload files and send JSON payload from a Frontend Single Page Application to your Laravel Backend API, you send it with a multipart/form-data encoding.</p><p>A typical example of doing this regardless of Frontend Frameworks would be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c40763650ffa44a187e615f40703435/href">https://medium.com/media/6c40763650ffa44a187e615f40703435/href</a></iframe><p>As a good Laravel developer, you want to validate this payload with a Laravel Request class before it comes to the Controller.</p><p>The Laravel Controller might look more or less like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b82fd95143b49b6d9a18861cd74da5e/href">https://medium.com/media/1b82fd95143b49b6d9a18861cd74da5e/href</a></iframe><p>and an example Laravel Request class would probably look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b8aede7a9afe9918d1fe95c963f84c4/href">https://medium.com/media/1b8aede7a9afe9918d1fe95c963f84c4/href</a></iframe><p>So far, everything went perfectly, but when you run this code, you will notice that the data you sent did not pass the validation. Dig deeper and you’ll see that the data coming into your Laravel API is very different from what we expected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Yf8rcRLy8drLI6jJnItvww.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04f902075a93195cc07029ea06ecbafa/href">https://medium.com/media/04f902075a93195cc07029ea06ecbafa/href</a></iframe><p>So you noticed that multipart/formdata, in addition to its ability to both, send binary files and JSON payload, converts all data types to strings,.</p><p>After this step, you can change your validation rules assuming that the incoming data will be all string types, you can do your parse gymnastics to fully validate string-type values.</p><h3>Validation with proper JSON Data Types</h3><p>If the FormData object can only send data of string types and we must use a FormData object to upload files, we will use it in this way. Of course, by first converting all the data to be sent to a JSON string.</p><p>After adding the file we want to upload to FormData (I.), we convert all the payload to a JSON string with the stringify() function. (II.)</p><p>Thus, we have a FormData object containing only the file and payload to send to the Backend API. (III.)</p><p>We used parseFloat() function because the stringify() function cannot parse float types to a JSON string with correct data type. (IV.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ceba2ebac58eff966b1690b3cb8bce60/href">https://medium.com/media/ceba2ebac58eff966b1690b3cb8bce60/href</a></iframe><p>We need to convert the JSON string coming to the Backend API side into a JSON Payload just before passing it through the validation rules. The prepareForValidation() method in Laravel’s Request classes is there for just that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6081c5a12ea1b359f119717c35e1b62/href">https://medium.com/media/d6081c5a12ea1b359f119717c35e1b62/href</a></iframe><p>After converting the JSON String to JSON Payload using the json_decode() function in the prepareForValidation() method, we combine it with other Request data with merge()which is another method of Laravel Request classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*f9keaVPM6XzVWBYyubr1Lg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d04ba5dee766715fe5b50789ec902720/href">https://medium.com/media/d04ba5dee766715fe5b50789ec902720/href</a></iframe><p>Thus, our data was cast into appropriate data types and passed all the validation rules. So there is no need to change the validation rules or do any additional validation gymnastics.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad3e40005a61" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tarfin/validating-multipart-form-data-with-laravel-validation-rules-with-proper-json-data-types-ad3e40005a61">Validating `multipart/form-data` with Laravel Validation Rules with proper JSON data types</a> was originally published in <a href="https://medium.com/tarfin">tarfin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel’de `multipart/form-data` İsteklerini doğru JSON Veri Tipleri ile Doğrulama]]></title>
            <link>https://medium.com/tarfin/laravelde-multipart-form-data-i%CC%87steklerini-do%C4%9Fru-json-veri-tipleri-ile-do%C4%9Frulama-888284bad42?source=rss----1ce425a134e4---4</link>
            <guid isPermaLink="false">https://medium.com/p/888284bad42</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[validation-rule]]></category>
            <category><![CDATA[upload]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Emre Deligöz]]></dc:creator>
            <pubDate>Thu, 13 Jan 2022 06:45:19 GMT</pubDate>
            <atom:updated>2022-08-25T20:19:13.977Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LTc7xp6wKMh9xtAnubCuhg.jpeg" /><figcaption>Fotoğraf: <a href="https://unsplash.com/@benofthenorth">Ben Griffiths</a> / <a href="https://unsplash.com/photos/4wxWBy8Jo1I">Unsplash</a></figcaption></figure><p>Bu makale <a href="https://medium.com/@deligoez">Yunus Emre Deligöz</a>, <a href="https://medium.com/@oguzhan.karacabay">Oğuzhan Karacabay</a> tarafından beraber yazılmıştır ve hem <a href="https://medium.com/tarfin/validating-multipart-form-data-with-laravel-validation-rules-with-proper-json-data-types-ad3e40005a61">İngilizce</a> hem de <a href="https://medium.com/tarfin/laravelde-multipart-form-data-i%CC%87steklerini-do%C4%9Fru-json-veri-tipleri-ile-do%C4%9Frulama-888284bad42">Türkçe</a> dillerinde okunabilir. Ayrıca <a href="https://deligoz.me/tr/makaleler/laravelde-multipartform-data-isteklerini-dogru-json-veri-tipleri-ile-dogrulama/">blogum</a> üzerinde okunabilir.</p><p>Bir Frontend SPA’dan Laravel Backend API’nize hem dosya yüklemek hem de JSON veri göndermek istediğinizde multipart/form-data şeklinde gönderirsiniz.</p><p>Frontend Framework’lardan bağımsız olarak bunu yapmanın tipik bir örneği şöyle olabilir:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c40763650ffa44a187e615f40703435/href">https://medium.com/media/6c40763650ffa44a187e615f40703435/href</a></iframe><p>Frontend’ten gelen bu isteği Backend API’de, iyi bir Laravel geliştiricisi olarak, Controller&#39;a uğramadan önce, bir Request ile doğrulamak istersiniz.</p><p>Laravel Controller’u da aşağı yukarı şuna benzer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/877ce3f75447b7a3b6d35a57faa5a929/href">https://medium.com/media/877ce3f75447b7a3b6d35a57faa5a929/href</a></iframe><p>Veriler ve yüklenecek dosya Controller’a gelmeden önce şuna benzer bir Request ile doğrulanır:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/625e326a45fb75763dee4f3e5c0cdf5c/href">https://medium.com/media/625e326a45fb75763dee4f3e5c0cdf5c/href</a></iframe><p>Buraya kadar her şey mükemmel ilerledi fakat bu kodu çalıştırdığınızda, gönderdiğiniz verilerin doğrulamadan geçemediğini ve derinlemesine incelediğinizde Laravel API’nize gelen verilerin beklediğimizden çok farklı olduğunu farkedeceksiniz:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yf8rcRLy8drLI6jJnItvww.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0283e7d48e7d52a917308b92df50a61b/href">https://medium.com/media/0283e7d48e7d52a917308b92df50a61b/href</a></iframe><p>Böylece multipart/formdata’nın binary dosya gönderebilme yeteneğinin yanında, bütün veri tiplerini string’lere çevirdiğini farkettiniz.</p><p>Bu aşamadan sonra gelen verileri API tarafında doğrulama kurallarınıza gelen verilerin string olacağını varsayarak değiştirdikten sonra, string tipindeki değerleri tam olarak doğrulamak için kendi parse jimnastiğinizi yapabilirsiniz.</p><h3>Doğru JSON Veri Tipleri ile Doğrulama</h3><p>Eğer FormData nesnesi sadece string türünde veri gönderebiliyor ve dosya yüklemek için mutlaka FormData nesnesi kullanmamız gerekiyorsa biz de öyle yaparız. Tabii ki öncesinde gönderilecek verilerin hepsini bir JSON string&#39;e çevirerek.</p><p>Frontend tarafında yüklemek istediğimiz dosyayı FormData’ya ekledikten sonra (I.) tüm diğer tüm verileri stringify() ile bir JSON string’e çeviriyoruz. (II.)</p><p>Böylece Backend API’sine göndermek üzere, elimizde sadece file ve payload verilerini içeren bir FormData nesnesi olmuş oldu. (III.)</p><p>stringify() fonksiyonu float tipindeki verileri JSON string’e doğru veri tipiyle aktaramadığı için parseFloat() fonksiyonunu kullandık. (IV.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9de9dc8cdcc2e66e701dbbfc6a2afe5a/href">https://medium.com/media/9de9dc8cdcc2e66e701dbbfc6a2afe5a/href</a></iframe><p>Backend API tarafına gelen JSON string&#39;i doğrulama kurallarından geçirmeden hemen önce bir JSON Payload&#39;a çevirmemiz gerekiyor. Laravel’in Request sınıflarındaki prepareForValidation() metodu da tam da bu iş için var.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6081c5a12ea1b359f119717c35e1b62/href">https://medium.com/media/d6081c5a12ea1b359f119717c35e1b62/href</a></iframe><p>prepareForValidation() metodu içinde JSON String’i json_decode() fonksiyonunu kullanarak JSON Payload’a çevirdikten sonra yine Laravel Request sınıflarının diğer bir metodu olan merge() ile diğer Request verileriyle birleştiriyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f9keaVPM6XzVWBYyubr1Lg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06a89fb2018aa33d6f0ff75ca1abe982/href">https://medium.com/media/06a89fb2018aa33d6f0ff75ca1abe982/href</a></iframe><p>Böylece verilerimiz uygun veri tiplerine cast edilerek doğrulama kurallarından geçebilmiş oldu. Ne doğrulama kurallarını değiştirmeye ne de ayrıca doğrulama jimnastiği yapmaya gerek kaldı.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=888284bad42" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tarfin/laravelde-multipart-form-data-i%CC%87steklerini-do%C4%9Fru-json-veri-tipleri-ile-do%C4%9Frulama-888284bad42">Laravel’de `multipart/form-data` İsteklerini doğru JSON Veri Tipleri ile Doğrulama</a> was originally published in <a href="https://medium.com/tarfin">tarfin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>