<?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 Ferdy Hahan Pradana on Medium]]></title>
        <description><![CDATA[Stories by Ferdy Hahan Pradana on Medium]]></description>
        <link>https://medium.com/@ferdyhape?source=rss-73ca9457d692------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HjUSeeaVMVnwWgCa5EMZTg.jpeg</url>
            <title>Stories by Ferdy Hahan Pradana on Medium</title>
            <link>https://medium.com/@ferdyhape?source=rss-73ca9457d692------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 11:50:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ferdyhape/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 Throttle vs Rate Limiting Explained: The 429 Error You’ve Caused]]></title>
            <link>https://ferdyhape.medium.com/laravel-throttle-vs-rate-limiting-explained-the-429-error-youve-caused-099fa08ab926?source=rss-73ca9457d692------2</link>
            <guid isPermaLink="false">https://medium.com/p/099fa08ab926</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ferdy Hahan Pradana]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 19:09:56 GMT</pubDate>
            <atom:updated>2026-08-11T19:09:56.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*He7CLbq3-UrgQf9h87ZBIA.png" /></figure><h3>The Day My API Learned What 429 Means</h3><p>Ever hit refresh one too many times and get slapped with “429 Too Many Requests”?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gASIjLnVAxpbNcSQYrIi3A.jpeg" /></figure><p>Maybe it was Cloudflare’s grumpy little error screen, maybe some API you were hammering with Postman at 2 A.M. That’s a rate limiter deciding you didn’t deserve another request just yet.</p><p>Now flip sides. You ship a public API endpoint, someone hits it with a script 400 times a second, and suddenly you’re the one handing out that exact same 429. Welcome to throttling. ☕</p><p>Here’s the thing though. A lot of people (past me included) use “throttle” and “rate limit” like they’re the exact same word. They’re cousins, not twins. Let’s sort that out first, then get our hands dirty with how Laravel actually handles this out of the box.</p><h3>WTF is the Difference, Actually?</h3><p><strong>Rate limiting</strong> is the <em>rule</em>. It’s the policy that says: “This client gets 60 requests per minute. No more, no less.” It’s the bouncer’s guest list.</p><p><strong>Throttling</strong> is the <em>enforcement</em>. It’s what actually happens when someone tries to walk past that list anyway: reject them, delay them, or make them wait their turn. It’s the bouncer physically standing in the doorway.</p><p>In plain English: rate limiting defines the ceiling, throttling is what slams the door once you hit it.</p><p>Funny enough, Laravel kind of smashes both concepts into one word and calls the whole thing throttle. The middleware is literally named throttle, and under the hood it&#39;s powered by a class called RateLimiter. So don&#39;t be surprised when you see both terms flying around interchangeably in Laravel docs. Just know that conceptually, they&#39;re not identical twins, they&#39;re siblings that showed up wearing the same jacket.</p><p>Here’s the whole thing in one picture, the rule on the left, the enforcement on the right, plus what the request window actually looks like once you hit 60 in a minute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zUwvGBb5Mg7rnfma0fJuQA.png" /></figure><h3>Enter Laravel’s Built-in Throttle Middleware</h3><p>Laravel doesn’t make you build this from scratch. It ships with rate limiting baked right in, sitting quietly in your RouteServiceProvider (or bootstrap/app.php / AppServiceProvider if you&#39;re on Laravel 11+).</p><p>Here’s a route with zero protection, wide open to anyone with a for-loop and bad intentions:</p><pre>Route::get(&#39;/posts&#39;, [PostController::class, &#39;index&#39;]);</pre><p>No limit means no mercy. Bolt on throttle and you&#39;re basically done:</p><pre>Route::middleware(&#39;throttle:60,1&#39;)-&gt;get(&#39;/posts&#39;, [PostController::class, &#39;index&#39;]);</pre><p>Read that as: <em>60 requests, every 1 minute.</em> Cross that line, and Laravel slams the door with a 429 Too Many Requests before your controller even gets a chance to say hello.</p><p>But hardcoding numbers straight into your routes gets messy fast, especially when you’ve got that same limit sprinkled across ten different routes. So Laravel gives you named limiters via the RateLimiter facade:</p><pre>use Illuminate\Cache\RateLimiting\Limit;<br>use Illuminate\Support\Facades\RateLimiter;</pre><pre>RateLimiter::for(&#39;api&#39;, function (Request $request) {<br>    return Limit::perMinute(60)-&gt;by($request-&gt;user()?-&gt;id ?: $request-&gt;ip());<br>});</pre><p>Now instead of a magic number scattered everywhere, your routes just point at a name:</p><pre>Route::middleware(&#39;throttle:api&#39;)-&gt;group(function () {<br>    Route::get(&#39;/data&#39;, [DataController::class, &#39;index&#39;]);<br>});</pre><p>One source of truth. Change the limit once in your service provider, and every route using throttle:api obeys it. No hunting through your routes file at 11 P.M. wondering why three endpoints have three different limits. 🧙‍♂️</p><h3>Give It a Personality: Limiting by User, Not Just IP</h3><p>Notice that -&gt;by() call up there? That&#39;s where the real power is. By default, throttling identifies clients by IP, but IPs are messy (hello, shared office networks and mobile carriers). If your users are authenticated, limit by user ID instead:</p><pre>RateLimiter::for(&#39;uploads&#39;, function (Request $request) {<br>    return $request-&gt;user()<br>        ? Limit::perMinute(10)-&gt;by($request-&gt;user()-&gt;id)<br>        : Limit::perMinute(3)-&gt;by($request-&gt;ip());<br>});</pre><p>Logged-in users get a friendlier limit, anonymous guests get the tighter leash. Same middleware, two different personalities depending on who’s knocking.</p><h3>What Actually Happens When Someone Gets Throttled?</h3><p>When a client blows past the limit, Laravel doesn’t just shrug. It responds with:</p><ul><li><strong>Status code </strong><strong>429 Too Many Requests</strong></li><li><strong>Retry-After</strong> header: how many seconds until they&#39;re allowed back in</li><li><strong>X-RateLimit-Limit</strong> and <strong>X-RateLimit-Remaining</strong>, so well-behaved clients can self-regulate instead of guessing</li></ul><p>If the default JSON error isn’t your vibe, you can customize the response per limiter:</p><pre>RateLimiter::for(&#39;api&#39;, function (Request $request) {<br>    return Limit::perMinute(60)<br>        -&gt;by($request-&gt;ip())<br>        -&gt;response(function (Request $request, array $headers) {<br>            return response()-&gt;json([<br>                &#39;message&#39; =&gt; &#39;Whoa, slow down there. Try again in a bit.&#39;,<br>            ], 429, $headers);<br>        });<br>});</pre><p>Same rejection, friendlier tone. Your API users will thank you for not just throwing a wall of red at them.</p><h3>The Moral of the Story</h3><p>Rate limiting is the rule you write once. Throttling is Laravel enforcing it every single time, automatically, without you lifting a finger at 3 A.M. when someone decides your /login endpoint looks fun to brute-force.</p><p>Set your limits before you need them, not after your database learns to cry. 😵‍💫</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=099fa08ab926" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel Observers Explained: A Guide to Eloquent Lifecycle Events]]></title>
            <link>https://ferdyhape.medium.com/laravel-observers-explained-a-guide-to-eloquent-lifecycle-events-a1ddeed3b1d3?source=rss-73ca9457d692------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1ddeed3b1d3</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[eloquent]]></category>
            <category><![CDATA[laravel-observer]]></category>
            <dc:creator><![CDATA[Ferdy Hahan Pradana]]></dc:creator>
            <pubDate>Sun, 31 May 2026 11:30:11 GMT</pubDate>
            <atom:updated>2026-05-31T11:30:11.961Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NUFlzFI8SjKRFQnsj36ig.png" /></figure><h3><strong>The Day My Controller Became a Junk Drawer</strong></h3><p>So, the other day I was wrestling with React hooks and component lifecycles (you know, the classic frontend mid-life crisis 😅). Amidst the chaos of state management and endless re-renders, a sudden thought struck me:</p><blockquote>“Wait, doesn’t Laravel Eloquent have its own lifecycle events too?”</blockquote><p>That simple question sent me straight back to the official documentation at <a href="https://laravel.com/docs/13.x/eloquent">https://laravel.com/docs/13.x/eloquent</a>. It made me realize a painful truth: <strong>if you’re not using model lifecycle events, you’re probably writing way too much copy-paste spaghetti.</strong> Let’s look at how to stop treating your controllers like a junk drawer, shall we?</p><h3>The Instant Dopamine Hit: From 60 Lines of Spaghetti to Exactly One Line</h3><p>Before we dive into the painful details, let me show you the reward at the end of this journey. Here is the visual contrast we are aiming for:</p><pre>// BEFORE: Manual SKU, Slug, and Image upload logic in every single controller 🤢<br>$data[&#39;sku&#39;] = &#39;P&#39; . str_pad(Product::max(&#39;id&#39;) + 1, 6, &#39;0&#39;, STR_PAD_LEFT);<br>$data[&#39;slug&#39;] = Str::slug($request-&gt;name) . &#39;-&#39; . time();<br>$data[&#39;image&#39;] = $this-&gt;handleUpload($request);<br>Product::create($data);<br><br>// AFTER: Sleek one-liner. The background logic is completely automated 😎<br>Product::create($request-&gt;validated());</pre><p>Imagine having that clean, one-line model action not just in your web dashboard, but in your REST API endpoints and background Excel imports too. <strong>No extra lines. No copy-pasting.</strong></p><p>To help you visualize how massive this architectural shift is, let’s look at how the data flows in both scenarios:</p><h4>The Old Way: Duplication Hell 🤢</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*MCAI2TsZyxjy5HZ3aOTlgQ.png" /></figure><h4>The New Way: Observer Magic 😎</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*cUVIZylWnA8dro__WNh0Mw.png" /></figure><p>Intrigued? Let’s get our hands dirty, shall we?</p><h3>Imagine this</h3><p>You’re building a classic product inventory system. You’ve got a simple products table with this database migration schema:</p><pre>Schema::create(&#39;products&#39;, function (Blueprint $table) {<br>    $table-&gt;id();<br>    $table-&gt;string(&#39;sku&#39;)-&gt;unique();       // Unique SKU code (like P000001)<br>    $table-&gt;string(&#39;slug&#39;)-&gt;unique();      // URL SEO slug<br>    $table-&gt;string(&#39;name&#39;);                // Product name<br>    $table-&gt;text(&#39;description&#39;)-&gt;nullable();<br>    $table-&gt;decimal(&#39;price&#39;, 12, 2);<br>    $table-&gt;string(&#39;image&#39;)-&gt;nullable();   // Image file path<br>    $table-&gt;timestamps();<br>    $table-&gt;softDeletes();<br>});</pre><p>And of course, to keep your data safe, you’ve got some validation rules in StoreProductRequest and UpdateProductRequest:</p><pre>// Rules on both StoreProductRequest &amp; UpdateProductRequest<br>public function rules(): array<br>{<br>    return [<br>        &#39;name&#39; =&gt; &#39;required|string|max:255&#39;,<br>        &#39;description&#39; =&gt; &#39;nullable|string&#39;,<br>        &#39;price&#39; =&gt; &#39;required|numeric|min:0&#39;,<br>        &#39;image&#39; =&gt; &#39;nullable|image|mimes:jpeg,png,jpg,gif|max:2048&#39;,<br>    ];<br>}</pre><h3>The Nightmare: Copy-Paste Hell (Before)</h3><p>Three years ago, if I needed to auto-generate a unique SKU, create a URL slug, and upload product images, I would hardcode all that logic inside the controller. Because, “<em>hey, it works, right?</em>”</p><p>Here is what ProductController.php looked like back then:</p><pre>class ProductController extends Controller<br>{<br>    public function store(StoreProductRequest $request)<br>    {<br>        $data = $request-&gt;validated();<br><br>        // 1. Manual SKU Generation<br>        $nextId = Product::max(&#39;id&#39;) + 1;<br>        $data[&#39;sku&#39;] = &#39;P&#39; . str_pad($nextId, 6, &#39;0&#39;, STR_PAD_LEFT);<br><br>        // 2. Manual Slug Generation<br>        $data[&#39;slug&#39;] = Str::slug($request-&gt;name) . &#39;-&#39; . time();<br><br>        // 3. Manual Image Upload<br>        if ($request-&gt;hasFile(&#39;image&#39;)) {<br>            $imageName = time() . &#39;.&#39; . $request-&gt;image-&gt;extension();<br>            $request-&gt;image-&gt;move(public_path(&#39;images&#39;), $imageName);<br>            $data[&#39;image&#39;] = &#39;images/&#39; . $imageName;<br>        }<br><br>        Product::create($data);<br><br>        return redirect()-&gt;route(&#39;products.index&#39;)-&gt;with(&#39;success&#39;, &#39;Product created successfully.&#39;);<br>    }<br><br>    public function update(UpdateProductRequest $request, Product $product)<br>    {<br>        $data = $request-&gt;validated();<br><br>        // Regenerate slug if product name changed<br>        if ($product-&gt;name !== $request-&gt;name) {<br>            $data[&#39;slug&#39;] = Str::slug($request-&gt;name) . &#39;-&#39; . time();<br>        }<br><br>        // Upload new image and clean up the old one<br>        if ($request-&gt;hasFile(&#39;image&#39;)) {<br>            if ($product-&gt;image &amp;&amp; file_exists(public_path($product-&gt;image))) {<br>                unlink(public_path($product-&gt;image));<br>            }<br><br>            $imageName = time() . &#39;.&#39; . $request-&gt;image-&gt;extension();<br>            $request-&gt;image-&gt;move(public_path(&#39;images&#39;), $imageName);<br>            $data[&#39;image&#39;] = &#39;images/&#39; . $imageName;<br>        }<br><br>        $product-&gt;update($data);<br><br>        return redirect()-&gt;route(&#39;products.index&#39;)-&gt;with(&#39;success&#39;, &#39;Product updated successfully.&#39;);<br>    }<br>}</pre><h3>The Chaos Expands</h3><p>Now, your application starts growing. Suddenly, creating a product doesn’t just happen from your admin web dashboard. You get two brand new entry points:</p><ol><li><strong>API/ProductController.php</strong>: Your mobile apps need a REST API to let sellers create products remotely.</li><li><strong>ImportProductsJob.php</strong>: A background job that imports thousands of products from a supplier’s CSV/Excel sheet.</li></ol><p>Since all that SKU, Slug, and Image logic is hardcoded inside the dashboard controller, you are forced to copy-paste the exact same messy blocks to your new files.</p><p><strong>1. Duplication in the API Controller (</strong><strong>API/ProductController.php)</strong></p><pre>public function store(Request $request)<br>{<br>    $data = $request-&gt;validate([<br>        &#39;name&#39; =&gt; &#39;required|string|max:255&#39;,<br>        &#39;price&#39; =&gt; &#39;required|numeric|min:0&#39;,<br>        &#39;image&#39; =&gt; &#39;nullable|image|mimes:jpeg,png,jpg,gif|max:2048&#39;,<br>    ]);<br><br>    // COPY-PASTE AGAIN: Generate SKU<br>    $nextId = Product::max(&#39;id&#39;) + 1;<br>    $data[&#39;sku&#39;] = &#39;P&#39; . str_pad($nextId, 6, &#39;0&#39;, STR_PAD_LEFT);<br><br>    // COPY-PASTE AGAIN: Generate Slug<br>    $data[&#39;slug&#39;] = Str::slug($request-&gt;name) . &#39;-&#39; . time();<br><br>    // COPY-PASTE AGAIN: Image Upload<br>    if ($request-&gt;hasFile(&#39;image&#39;)) {<br>        $imageName = time() . &#39;.&#39; . $request-&gt;image-&gt;extension();<br>        $request-&gt;image-&gt;move(public_path(&#39;images&#39;), $imageName);<br>        $data[&#39;image&#39;] = &#39;images/&#39; . $imageName;<br>    }<br><br>    $product = Product::create($data);<br><br>    return response()-&gt;json($product, 201);<br>}</pre><p><strong>2. Duplication in the Background Import Job (</strong><strong>ImportProductsJob.php)</strong></p><pre>foreach ($rows as $row) {<br>    // COPY-PASTE AGAIN: Generate SKU &amp; Slug<br>    $nextId = Product::max(&#39;id&#39;) + 1;<br>    $sku = &#39;P&#39; . str_pad($nextId, 6, &#39;0&#39;, STR_PAD_LEFT);<br>    $slug = Str::slug($row[&#39;product_name&#39;]) . &#39;-&#39; . time();<br><br>    Product::create([<br>        &#39;sku&#39; =&gt; $sku,<br>        &#39;slug&#39; =&gt; $slug,<br>        &#39;name&#39;  =&gt; $row[&#39;product_name&#39;],<br>        &#39;price&#39; =&gt; $row[&#39;price&#39;],<br>    ]);<br>}</pre><p><strong>Write once, copy everywhere.</strong> This architecture is incredibly fragile. If your boss decides that SKUs must start with PROD- instead of P, you now have to search and update your code in three separate files. If you forget one? Congratulations, you just bought yourself a VIP ticket to a 3 A.M. Slack ping session with your manager. 😂</p><p>If we draw a map of this architecture, it becomes painfully obvious how fragile and fragmented our application is becoming:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*MCAI2TsZyxjy5HZ3aOTlgQ.png" /></figure><h3>The Solution: Building <em>ProductObserver</em></h3><p>Alright, enough chit-chat like 🙍‍♀️. Let’s bundle all that manual SKU, Slug, and file uploading code, and move it into one clean home: <strong>ProductObserver.php</strong>!</p><p><strong>1. The Observer — Let’s Build the Hero First!</strong></p><p>First, run this artisan command to instantly scaffold our observer pre-linked with our Product model:</p><pre>php artisan make:observer ProductObserver --model=Product</pre><p>This will generate a template inside app/Observers/ProductObserver.php. Let&#39;s open it up and place all of our model automation logic inside:</p><pre>namespace App\Observers;<br><br>use App\Models\Product;<br>use Illuminate\Support\Str;<br><br>class ProductObserver<br>{<br>    /**<br>     * Run automatically BEFORE a new product is saved<br>     */<br>    public function creating(Product $product): void<br>    {<br>        // Generate a unique SKU automatically <br>        $nextId = Product::max(&#39;id&#39;) + 1;<br>        $product-&gt;sku = &#39;P&#39; . str_pad($nextId, 6, &#39;0&#39;, STR_PAD_LEFT);<br><br>        // Generate a slug automatically <br>        $product-&gt;slug = Str::slug($product-&gt;name) . &#39;-&#39; . time();<br>    }<br><br>    /**<br>     * Run automatically BEFORE an existing product is updated<br>     */<br>    public function updating(Product $product): void<br>    {<br>        // Regenerate the slug only if the product name changed <br>        if ($product-&gt;isDirty(&#39;name&#39;)) {<br>            $product-&gt;slug = Str::slug($product-&gt;name) . &#39;-&#39; . time();<br>        }<br>    }<br><br>    /**<br>     * Run automatically BEFORE saving (Create &amp; Update)<br>     */<br>    public function saving(Product $product): void<br>    {<br>        // Handle file upload if a new image is sent <br>        if (request()-&gt;hasFile(&#39;image&#39;)) {<br>            // Clean up the old image file if updating<br>            if ($product-&gt;exists &amp;&amp; $product-&gt;isDirty(&#39;image&#39;) &amp;&amp; $product-&gt;getOriginal(&#39;image&#39;)) {<br>                $oldImage = $product-&gt;getOriginal(&#39;image&#39;);<br>                if (file_exists(public_path($oldImage))) {<br>                    unlink(public_path($oldImage));<br>                }<br>            }<br><br>            $image = request()-&gt;file(&#39;image&#39;);<br>            $imageName = time() . &#39;.&#39; . $image-&gt;getClientOriginalExtension();<br>            $image-&gt;move(public_path(&#39;images&#39;), $imageName);<br>            $product-&gt;image = &#39;images/&#39; . $imageName;<br>        }<br>    }<br><br>    /**<br>     * Run automatically BEFORE a product is deleted<br>     */<br>    public function deleting(Product $product): void<br>    {<br>        // Clean up the physical image from the server to save space <br>        if ($product-&gt;image &amp;&amp; file_exists(public_path($product-&gt;image))) {<br>            unlink(public_path($product-&gt;image));<br>        }<br>    }<br>}</pre><p><strong>2. The Registration — Making It Official</strong></p><p>After creating our ProductObserver, we need to let Laravel know it should watch the Product model. Think of this like updating your relationship status on Facebook 🤣, but Laravel-style. You’ve got two modern ways to make this happen:</p><p><strong>Option 1: PHP Attributes (The Modern Laravel Way)</strong></p><p>In the latest versions of Laravel, you can register observers directly inside the Model class using PHP Attributes. This is incredibly clean because you don’t even have to open a Service Provider class. Just open your Product.php model and add the attribute:</p><pre>namespace App\Models;<br><br>use App\Observers\ProductObserver;<br>use Illuminate\Database\Eloquent\Attributes\ObservedBy;<br>use Illuminate\Database\Eloquent\Model;<br><br>#[ObservedBy([ProductObserver::class])] // This line right here is the  magic <br>class Product extends Model<br>{<br>    // Your model properties and relations...<br>}</pre><p><strong>Option 2: Manual Registration in AppServiceProvider</strong></p><p>If you prefer centralizing your registrations, or if you are working on an older Laravel codebase, you can manually register it inside the boot method of app/Providers/AppServiceProvider.php:</p><pre>class AppServiceProvider extends ServiceProvider<br>{<br>    public function boot(): void<br>    {<br>        Product::observe(ProductObserver::class);<br>    }<br>}</pre><p><strong>3. The Clean Slate — Total Extermination (After)</strong></p><p>With our observer registered, let’s look at how clean, readable, and beautiful all our entry points become. Think of this like taking a deep breath after being underwater:</p><ul><li><strong>Web Controller (</strong><strong>ProductController.php)</strong></li></ul><pre>class ProductController extends Controller<br>{<br>    public function store(StoreProductRequest $request)<br>    {<br>        Product::create($request-&gt;validated());<br>        return redirect()-&gt;route(&#39;products.index&#39;)-&gt;with(&#39;success&#39;, &#39;Product created successfully.&#39;);<br>    }<br><br>    public function update(UpdateProductRequest $request, Product $product)<br>    {<br>        $product-&gt;update($request-&gt;validated());<br>        return redirect()-&gt;route(&#39;products.index&#39;)-&gt;with(&#39;success&#39;, &#39;Product updated successfully.&#39;);<br>    }<br>}</pre><ul><li><strong>REST API Controller (</strong><strong>API/ProductController.php)</strong></li></ul><pre>public function store(Request $request)<br>{<br>    $data = $request-&gt;validate([<br>        &#39;name&#39; =&gt; &#39;required|string|max:255&#39;,<br>        &#39;price&#39; =&gt; &#39;required|numeric|min:0&#39;,<br>        &#39;image&#39; =&gt; &#39;nullable|image|mimes:jpeg,png,jpg,gif|max:2048&#39;,<br>    ]);<br><br>    $product = Product::create($data);<br><br>    return response()-&gt;json($product, 201);<br>}</pre><ul><li><strong>Background Excel Import (</strong><strong>ImportProductsJob.php)</strong></li></ul><pre>foreach ($rows as $row) {<br>    Product::create([<br>        &#39;name&#39;  =&gt; $row[&#39;product_name&#39;],<br>        &#39;price&#39; =&gt; $row[&#39;price&#39;],<br>    ]);<br>}</pre><p>Your controllers are now so thin they could practically slide under a closed door. 😂 No more copying and pasting lines of code like a modern-day digital scribe. Just clean, predictable, stress-free code that does exactly what you expect it to do. 💻</p><h3>The Concept: Eloquent Lifecycle Events Cheat Sheet</h3><p>So… what’s the secret behind this magic? 🧙‍♂️ Instead of copy-pasting code, we can utilize model lifecycle events. Every time a model is loaded, saved, updated, or deleted, Laravel dispatches a lifecycle event in the background.</p><p>Here is the complete cheat sheet of all 15 Eloquent lifecycle events, explained simply:</p><ul><li><strong>retrieved</strong> (After loaded): Fired after a model is successfully loaded from the database.</li><li><strong>creating</strong> (Before insert): Fired before a brand-new model is saved for the first time. (Our hero for generating SKUs and slugs!)</li><li><strong>created</strong> (After insert): Fired after a new model is successfully saved to the database.</li><li><strong>updating</strong> (Before update): Fired before an existing model is updated.</li><li><strong>updated</strong> (After update): Fired after an existing model is successfully updated.</li><li><strong>saving</strong> (Before save): Fired before a model is written to the database (runs on both insert and update).</li><li><strong>saved</strong> (After save): Fired after a model is successfully saved (runs on both insert and update).</li><li><strong>deleting</strong> (Before delete): Fired before a model is deleted. (The perfect place to clean up physical storage files!)</li><li><strong>deleted</strong> (After delete): Fired after a model is successfully deleted.</li><li><strong>trashed</strong> (After soft-delete): Fired after a model is soft-deleted.</li><li><strong>forceDeleting</strong> (Before hard-delete): Fired before a model is permanently deleted.</li><li><strong>forceDeleted</strong> (After hard-delete): Fired after a model is permanently deleted.</li><li><strong>restoring</strong> (Before restore): Fired before a soft-deleted model is restored.</li><li><strong>restored</strong> (After restore): Fired after a soft-deleted model is successfully restored.</li><li><strong>replicating</strong> (During clone): Fired when a model is being cloned using the replicate() method.</li></ul><p>By harnessing these events via our ProductObserver, we establish a clean, centralized middle-man that intercepts model operations. Here is how our refined, DRY architecture flows now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*cUVIZylWnA8dro__WNh0Mw.png" /></figure><h3>Final Thoughts: The Single Source of Truth Pattern</h3><p>Shifting lifecycle logic into <strong>Eloquent Observers</strong> establishes a robust <strong>Single Source of Truth</strong>. In our study case, generating SKUs, slugs, and uploading images served as a perfect illustration of how to consolidate fragmented logic. By binding these operations to model events, they are guaranteed to run consistently-whether triggered by a web controller, API controller, background job, or database seeder.</p><h4>Quick Decision Guide:</h4><ul><li><strong>Use Observers for</strong>: Centralized automations (e.g., generating default values), disk cleanups (e.g., deleting orphaned images when a record is deleted), and simple side effects (e.g., firing a welcome email or logging activity).</li><li><strong>Avoid Observers for</strong>: Complex or heavy external API calls that can slow down your database transactions. Keep database-adjacent logic database-adjacent!</li></ul><p>Next time you find yourself copy-pasting lifecycle logic across multiple controllers, stop and ask yourself: <em>“Can I move this to an observer?”</em> Keep your controllers slim, your code DRY, and let Laravel’s model events do the heavy lifting!</p><h4>And That’s a Wrap!</h4><p>Cool, right? Almost magical. With Eloquent observers, you can centralize all your model lifecycles in one clean home-leaving your controllers absolutely pristine.</p><p>So instead of spending your precious coding hours copy-pasting the same logic across different files, you can finally focus on more critical engineering features-like, you know, building a Slack bot that automatically praises your manager’s new haircut (kidding… 😅).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1ddeed3b1d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Day Laravel Let Two Buyers Win - A Race Condition Story]]></title>
            <link>https://ferdyhape.medium.com/the-day-laravel-let-two-buyers-win-a-race-condition-story-238b4c73e9b9?source=rss-73ca9457d692------2</link>
            <guid isPermaLink="false">https://medium.com/p/238b4c73e9b9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[race-condition]]></category>
            <dc:creator><![CDATA[Ferdy Hahan Pradana]]></dc:creator>
            <pubDate>Thu, 23 Oct 2025 19:46:30 GMT</pubDate>
            <atom:updated>2025-10-23T19:46:30.025Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J3tcELFjMdvZLl7-2CpLGg.png" /></figure><h3>Imagine this.</h3><p>You’re on an e-commerce site, scrolling through endless outfits, and suddenly, boom! you find <em>the one!</em><br>The outfit that screams <em>“this will fix my love life.”</em></p><p>You click <strong>Buy</strong>.</p><p>At the exact same time, somewhere across the internet, another person (let’s call them <em>the payday warrior</em>) also clicks <strong>Buy</strong>.<br> Both of you are ready to shine on your next date.</p><p>There’s just one tiny problem…</p><p><strong>Stock = 1.</strong></p><h3>The Chaos Begins</h3><p>Both transactions reach the server.<br>Each says, “Hey, I saw stock = 1, I’m taking it.”</p><p>The server, being overly polite, replies to both:<br> “Sure! You both can have it.”</p><p>A few milliseconds later…</p><p><strong>Stock = -1.</strong></p><p>Wait, what?</p><p>Congratulations! you’ve just witnessed a <strong><em>race condition</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*HeU6gMyIC0Zuo_UpKRbqOw.png" /><figcaption>all icons from <a href="https://flaticon.com/">https://flaticon.com</a></figcaption></figure><h3>WTF is a Race Condition?</h3><p>A race condition happens when two (or more) operations try to access or modify the same data at the same time, and the final result depends on which one “wins” the race.</p><p>In our case:</p><ul><li>Buyer A reads stock = 1</li><li>Buyer B reads stock = 1</li><li>Both reduce it by 1</li><li>Final stock = -1</li></ul><p>Mathematically wrong.<br>Systemically tragic.<br>Database crying in the corner.</p><h3>How to Stop the Madness</h3><p>To fix this, we need to <strong>lock that stock record</strong> while one transaction is being processed, kind of like putting a “Do Not Disturb” sign on it.</p><p>In Laravel, this is as simple as:</p><pre>DB::transaction(function () use ($id) {<br>    $product = Product::where(&#39;id&#39;, $id)-&gt;lockForUpdate()-&gt;first();<br>    if ($product-&gt;stock &lt;= 0) {<br>        throw new \Exception(&#39;Out of stock&#39;);<br>    }<br>    $product-&gt;decrement(&#39;stock&#39;);<br>});</pre><p>Now, if you’re wondering <em>“Okay, but which line actually does the magic?”</em><br>It’s <strong>this one</strong> right here 👇</p><pre>$product = Product::where(&#39;id&#39;, $id)-&gt;lockForUpdate()-&gt;first();</pre><p>That single methodlockForUpdate()tells your database:</p><blockquote><em>“Hey, I’m using this row. Nobody else touches it until I’m done.”</em></blockquote><p>Everything inside the DB::transaction() block then runs safely.<br> The second buyer will have to wait until the first buyer’s transaction is complete before reading or modifying that product’s stock.</p><p>So to break it down:</p><ul><li>DB::transaction() → groups the operations into one atomic process (all or nothing).</li><li>lockForUpdate() → <strong>the real hero</strong> that prevents race conditions by locking the row.</li></ul><p>And just like that, your database keeps its dignity.<br>No more negative stock. No more midnight debugging.</p><h3>Moral of the Story</h3><p>Race conditions are sneaky, they don’t happen in your tests, but they’ll ruin your production data at 3 A.M.</p><p>So the next time your app does something that makes no logical sense (like selling ghost inventory), remember:<br>It’s not haunted, it’s just racing.</p><p>And in every race, someone loses.<br>Preferably, not your database.</p><h3><strong>Thanks for Reading</strong></h3><p>Thanks for sticking around till the end.<br>Race conditions like this don’t just happen in e-commerce, they can sneak into any system where two processes try to outsmart each other.<br>The stock example is just one face of the same mischievous bug.</p><p>So whether it’s users, background jobs, or microservices, remember:<br>when it comes to shared data, <strong>it’s not paranoia, it’s prevention.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=238b4c73e9b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keep It Clean: Make Your Laravel Code Cleaner and Smarter Using Accessors and Mutators]]></title>
            <link>https://ferdyhape.medium.com/keep-it-clean-make-your-laravel-code-cleaner-and-smarter-using-accessors-and-mutators-1c7fd8c2835d?source=rss-73ca9457d692------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c7fd8c2835d</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Ferdy Hahan Pradana]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 18:16:39 GMT</pubDate>
            <atom:updated>2025-04-26T18:16:39.768Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*drpscyLy_01io8CWvRq1pA.png" /></figure><h3>Keep Your Controller Light and Your Coffee Strong</h3><p>Controllers are supposed to manage the flow of your app.<br>But if you cram every tiny piece of logic in there — especially stuff you have to repeat everywhere — you’re just stealing your own coffee time. ☕</p><p>Sure, you can clean things up with Traits, Services, or Helpers. But today, let’s zoom in on something closer to the model: <strong>Accessors and Mutators</strong> — to keep your controllers slim, clean, and easy on the eyes.</p><h3>What’s the Deal with Accessors and Mutators?</h3><p>Imagine you’re storing user data in your database, including their address.<br> The data’s split across multiple columns: street_address, city, state, and postal_code.<br> But many times, you need the full address — like when:</p><ul><li>Showing it on the user’s profile page.</li><li>Sending a shipping confirmation email.</li><li>Displaying it during checkout.</li></ul><p>Now, without any special magic, you might end up repeating something like this all over your controllers:</p><pre>// ProfileController.php<br>public function show()<br>{<br>    $user = User::find(1);<br>    $street = $user-&gt;street_address;<br>    $city = $user-&gt;city;<br>    $state = $user-&gt;state;<br>    $postalCode = $user-&gt;postal_code;<br><br>    $fullAddress = $street . &#39;, &#39; . $city . &#39;, &#39; . $state . &#39; &#39; . $postalCode;<br><br>    return view(&#39;profile.show&#39;, compact(&#39;fullAddress&#39;));<br>}<br><br>// OrderController.php<br>public function confirm()<br>{<br>    $user = User::find(1);<br>    $street = $user-&gt;street_address;<br>    $city = $user-&gt;city;<br>    $state = $user-&gt;state;<br>    $postalCode = $user-&gt;postal_code;<br><br>    $fullAddress = $street . &#39;, &#39; . $city . &#39;, &#39; . $state . &#39; &#39; . $postalCode;<br><br>    return view(&#39;order.confirm&#39;, compact(&#39;fullAddress&#39;));<br>}<br><br>// NotificationController.php<br>public function send()<br>{<br>    $user = User::find(1);<br>    $street = $user-&gt;street_address;<br>    $city = $user-&gt;city;<br>    $state = $user-&gt;state;<br>    $postalCode = $user-&gt;postal_code;<br><br>    $fullAddress = $street . &#39;, &#39; . $city . &#39;, &#39; . $state . &#39; &#39; . $postalCode;<br><br>    Mail::to($user)-&gt;send(new AddressNotification($fullAddress));<br>}</pre><p>Exhausted just looking at it? Yeah, same. 😵‍💫</p><h3>The Smarter Way: Accessor to the Rescue</h3><p>Instead of stitching addresses together <em>again and again</em>, let’s build it once inside the User model:</p><pre>// User.php<br>public function getFullAddressAttribute()<br>{<br>    return $this-&gt;street_address . &#39;, &#39; . $this-&gt;city . &#39;, &#39; . $this-&gt;state . &#39; &#39; . $this-&gt;postal_code;<br>}</pre><p>Now in your controller, just grab full_address like any normal attribute:</p><pre>// ProfileController.php<br>public function show()<br>{<br>    $fullAddress = User::find(1)-&gt;full_address;<br>    return view(&#39;profile.show&#39;, compact(&#39;fullAddress&#39;));<br>}<br><br>// OrderController.php<br>public function confirm()<br>{<br>    $fullAddress = User::find(1)-&gt;full_address;<br>    return view(&#39;order.confirm&#39;, compact(&#39;fullAddress&#39;));<br>}<br><br>// NotificationController.php<br>public function send()<br>{<br>    $fullAddress = User::find(1)-&gt;full_address;<br>    Mail::to($user)-&gt;send(new AddressNotification($fullAddress));<br>}</pre><p>Way cleaner, right?<br>Your controller no longer looks like a messy buffet filled with leftover spaghetti code.</p><h3>Level Up Even More: Mutators Got You Covered</h3><p>While Accessors are great for <strong>reading</strong> pretty data, Mutators are perfect for <strong>saving</strong> polished data.</p><p>For example, you want every street_address automatically capitalized — no more manual fixing!</p><p>Teach your User model to handle it for you:</p><pre>// User.php<br>public function setStreetAddressAttribute($value)<br>{<br>    $this-&gt;attributes[&#39;street_address&#39;] = ucwords($value);<br>}</pre><p>So even if a user enters something like &quot;jalan raya jakarta&quot;, it gets stored nicely as &quot;Jalan Raya Jakarta&quot;.</p><p>When saving data:</p><pre>// UserController.php<br>public function store(Request $request)<br>{<br>    $user = new User();<br>    $user-&gt;street_address = &#39;jalan raya&#39;; // Will be saved as &#39;Jalan Raya&#39; automatically!<br>    $user-&gt;save();<br>}</pre><p>You don’t even have to think about formatting again.<br>Less thinking = more coffee = happier devs. ☕😎</p><h3>Final Thoughts: Write Less, Enjoy More</h3><p>By using Accessors and Mutators, you keep your controllers <strong>clean</strong>, <strong>organized</strong>, and <strong>beautiful</strong>.<br> No more endless copy-pasting. No more messy controllers. No more “Sorry bro, still fixing my code” when friends call you out for coffee. 🤣</p><p>Write smarter, code cleaner, live better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c7fd8c2835d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel Tips: Create a Flexible and Valuable Backend with Polymorphic Concept]]></title>
            <link>https://ferdyhape.medium.com/laravel-tips-create-a-flexible-and-valuable-backend-with-polymorphic-concept-aff5fca35fb2?source=rss-73ca9457d692------2</link>
            <guid isPermaLink="false">https://medium.com/p/aff5fca35fb2</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Ferdy Hahan Pradana]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 16:57:35 GMT</pubDate>
            <atom:updated>2025-05-04T23:24:06.913Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q6or8AfT5eO3f86duCOB7w.png" /></figure><h3>Write Once, Use Anywhere — Sounds Familiar?</h3><p>You’ve got comments in your Laravel app. But not just for posts.<br>Also for videos. Maybe even for your ex’s throwback story. (ouch 😅)</p><p><strong>One comment table for each?</strong> <strong>No thanks</strong>.</p><p>Laravel says:</p><blockquote>“One table to rule them all — Polymorphic style.”</blockquote><h3>So… What Even <em>Is</em> a Polymorphic Relationship?</h3><p>So here’s the deal…<br>Usually, when two models are connected, it’s either one-to-one, one-to-many, or many-to-many.<br>But sometimes, <strong>one model needs to be connected to <em>many</em> different models — in the same exact way</strong>.</p><p>An example?</p><p>Let’s say you’re building a simple social media app. You’ve got:</p><ul><li>Article posts</li><li>Video posts</li><li>And all of them can be commented on</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*CIrOEOJcGyBxnb5pKTqEtw.png" /><figcaption>simple social media app flow</figcaption></figure><p>Now, would you create separate tables like this?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*t_wq7YvaGMz9XtY1wVPjig.png" /><figcaption>separated comment table</figcaption></figure><p>Well… sure, you <em>could</em>.<br>But imagine having 10 different types of content — that’s 10 separate comment tables. That’s chaos 😱</p><p>Now look at this simpler version instead:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*_xEt1c9mhidnh1VVIzop9w.png" /><figcaption>comment table that is only one</figcaption></figure><p>Much better, right? Clean and efficient.<br>That’s the magic of a <strong>polymorphic relationship</strong> — it lets you connect one model to many others using the same relationship setup.</p><h3>So, How the Heck Do We Actually Use This in Laravel?</h3><p>Alright, enough chit-chat. Let’s get our hands dirty, shall we?</p><p>Let’s say we have three models: Article, Video, and Comment. Our goal here is to make a <em>happy little relationship</em> between Comment and both Article &amp; Video. Like a love triangle... but in code.</p><p><strong>1. The Migrations — Let’s Build the Tables First!</strong></p><p>We’ll start by creating tables for articles, videos, and comments. We&#39;re going to be cool and use UUIDs as the primary keys.</p><pre>// articles table<br>Schema::create(&#39;articles&#39;, function (Blueprint $table) {<br>    $table-&gt;id();<br>    $table-&gt;string(&#39;title&#39;);<br>    $table-&gt;text(&#39;body&#39;);<br>    $table-&gt;foreignUuid(&#39;user_id&#39;);<br>    $table-&gt;timestamps();<br>});<br><br>// videos table<br>Schema::create(&#39;videos&#39;, function (Blueprint $table) {<br>    $table-&gt;id();<br>    $table-&gt;string(&#39;title&#39;);<br>    $table-&gt;string(&#39;url&#39;);<br>    $table-&gt;foreignUuid(&#39;user_id&#39;);<br>    $table-&gt;timestamps();<br>});<br><br>// comments table<br>Schema::create(&#39;comments&#39;, function (Blueprint $table) {<br>    $table-&gt;id();<br>    $table-&gt;morphs(&#39;commentable&#39;); // This adds &#39;commentable_id&#39; &amp; &#39;commentable_type&#39; fields<br>    $table-&gt;text(&#39;comment&#39;);<br>    $table-&gt;foreignUuid(&#39;user_id&#39;);<br>    $table-&gt;timestamps();<br>});</pre><p><strong>Heads up!</strong> If your related models (like Article or Video) use UUIDs as IDs, then uuidMorphs is the way to go. If not, you can switch back to the regular morphs.</p><p><strong>2. The Models — Making Relationships Official</strong></p><p>Now, let’s define the relationships inside our models. Think of this like updating your relationship status on Facebook, but Laravel-style.</p><pre>class Article extends Model<br>{<br>    use HasFactory;<br><br>    protected $guarded = [&#39;id&#39;];<br><br>    public function comments()<br>    {<br>        return $this-&gt;morphMany(Comment::class, &#39;commentable&#39;);<br>    }<br>}<br><br>class Video extends Model<br>{<br>    use HasFactory;<br><br>    protected $guarded = [&#39;id&#39;];<br><br>    public function comments()<br>    {<br>        return $this-&gt;morphMany(Comment::class, &#39;commentable&#39;);<br>    }<br>}<br><br>class Comment extends Model<br>{<br>    use HasFactory;<br><br>    protected $guarded = [&#39;id&#39;];<br><br>    public function commentable()<br>    {<br>        return $this-&gt;morphTo(); // This line right here is the ✨ magic ✨<br>    }<br>}</pre><p><strong>3. Seeding Time — Populating Our Database with Fake Drama</strong></p><p>Alright, let’s drop in some dummy data with seeders — two articles and two videos, each with two comments. Drama incoming!</p><pre>class DatabaseSeeder extends Seeder<br>{<br>    public function run(): void<br>    {<br>        // Seeding Users<br>        \App\Models\User::factory(2)-&gt;create();<br><br>        // Seeding Articles with Comments<br>        for ($i = 0; $i &lt; 2; $i++) {<br>            Article::create([<br>                &#39;title&#39; =&gt; &#39;Article &#39; . ($i + 1),<br>                &#39;body&#39; =&gt; &#39;Content of article &#39; . ($i + 1),<br>                &#39;user_id&#39; =&gt; \App\Models\User::all()-&gt;random()-&gt;id,<br>            ])-&gt;comments()-&gt;createMany([<br>                [<br>                    &#39;comment&#39; =&gt; &#39;Comment 1 of article &#39; . ($i + 1),<br>                    &#39;user_id&#39; =&gt; \App\Models\User::all()-&gt;random()-&gt;id,<br>                ],<br>                [<br>                    &#39;comment&#39; =&gt; &#39;Comment 2 of article &#39; . ($i + 1),<br>                    &#39;user_id&#39; =&gt; \App\Models\User::all()-&gt;random()-&gt;id,<br>                ],<br>            ]);<br>        }<br><br>        // Seeding Videos with Comments<br>        for ($i = 0; $i &lt; 2; $i++) {<br>            Video::create([<br>                &#39;title&#39; =&gt; &#39;Video &#39; . ($i + 1),<br>                &#39;url&#39; =&gt; &#39;https://example.com/video&#39; . ($i + 1),<br>                &#39;user_id&#39; =&gt; \App\Models\User::all()-&gt;random()-&gt;id,<br>            ])-&gt;comments()-&gt;createMany([<br>                [<br>                    &#39;comment&#39; =&gt; &#39;Comment 1 of video &#39; . ($i + 1),<br>                    &#39;user_id&#39; =&gt; \App\Models\User::all()-&gt;random()-&gt;id,<br>                ],<br>                [<br>                    &#39;comment&#39; =&gt; &#39;Comment 2 of video &#39; . ($i + 1),<br>                    &#39;user_id&#39; =&gt; \App\Models\User::all()-&gt;random()-&gt;id,<br>                ],<br>            ]);<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*av2rXzLiHUqbBtoyxbn4og.png" /><figcaption>Articles Data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*aW9bJgXg2riPsnJU8PckMA.png" /><figcaption>Video Data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*9t1nL5aBZMS_wybFSloEww.png" /><figcaption>Comments Data</figcaption></figure><p><strong>4. Fetching Articles and Videos Along with Their Comments</strong></p><p>Now let’s pull the data from our articles and videos complete with their juicy comment threads. Laravel makes this stupidly easy.</p><pre>// ArticleController.php<br>public function index()<br>{<br>    $articles = Article::with(&#39;comments&#39;)-&gt;get();<br>    return response()-&gt;json($articles);<br>}<br><br>// VideoController.php<br>public function index()<br>{<br>    $videos = Video::with(&#39;comments&#39;)-&gt;get();<br>    return response()-&gt;json($videos);<br>}<br><br>// web.php<br>Route::get(&#39;/articles&#39;, [ArticleController::class, &#39;index&#39;]);<br>Route::get(&#39;/videos&#39;, [VideoController::class, &#39;index&#39;]);</pre><p>You’ll get something like this (yes, raw JSON, but still beautiful):</p><ul><li>Articles Data</li></ul><pre>[<br>    {<br>        &quot;id&quot;: 1,<br>        &quot;title&quot;: &quot;Article 1&quot;,<br>        &quot;body&quot;: &quot;Content of article 1&quot;,<br>        &quot;user_id&quot;: 2,<br>        &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>        &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>        &quot;comments&quot;: [<br>            {<br>                &quot;id&quot;: 1,<br>                &quot;commentable_type&quot;: &quot;App\\Models\\Article&quot;,<br>                &quot;commentable_id&quot;: &quot;1&quot;,<br>                &quot;comment&quot;: &quot;Comment 1 of article 1&quot;,<br>                &quot;user_id&quot;: 1,<br>                &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>                &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;<br>            },<br>            {<br>                &quot;id&quot;: 2,<br>                &quot;commentable_type&quot;: &quot;App\\Models\\Article&quot;,<br>                &quot;commentable_id&quot;: &quot;1&quot;,<br>                &quot;comment&quot;: &quot;Comment 2 of article 1&quot;,<br>                &quot;user_id&quot;: 2,<br>                &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>                &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;<br>            }<br>        ]<br>    },<br>    {<br>        &quot;id&quot;: 2,<br>        &quot;title&quot;: &quot;Article 2&quot;,<br>        &quot;body&quot;: &quot;Content of article 2&quot;,<br>        &quot;user_id&quot;: 1,<br>        &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>        &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>        &quot;comments&quot;: [<br>            {<br>                &quot;id&quot;: 3,<br>                &quot;commentable_type&quot;: &quot;App\\Models\\Article&quot;,<br>                &quot;commentable_id&quot;: &quot;2&quot;,<br>                &quot;comment&quot;: &quot;Comment 1 of article 2&quot;,<br>                &quot;user_id&quot;: 2,<br>                &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>                &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;<br>            },<br>            {<br>                &quot;id&quot;: 4,<br>                &quot;commentable_type&quot;: &quot;App\\Models\\Article&quot;,<br>                &quot;commentable_id&quot;: &quot;2&quot;,<br>                &quot;comment&quot;: &quot;Comment 2 of article 2&quot;,<br>                &quot;user_id&quot;: 2,<br>                &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>                &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;<br>            }<br>        ]<br>    }<br>]</pre><ul><li>Videos Data</li></ul><pre>[<br>    {<br>        &quot;id&quot;: 1,<br>        &quot;title&quot;: &quot;Video 1&quot;,<br>        &quot;url&quot;: &quot;https://example.com/video1&quot;,<br>        &quot;user_id&quot;: 1,<br>        &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>        &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>        &quot;comments&quot;: [<br>            {<br>                &quot;id&quot;: 5,<br>                &quot;commentable_type&quot;: &quot;App\\Models\\Video&quot;,<br>                &quot;commentable_id&quot;: &quot;1&quot;,<br>                &quot;comment&quot;: &quot;Comment 1 of video 1&quot;,<br>                &quot;user_id&quot;: 1,<br>                &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>                &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;<br>            },<br>            {<br>                &quot;id&quot;: 6,<br>                &quot;commentable_type&quot;: &quot;App\\Models\\Video&quot;,<br>                &quot;commentable_id&quot;: &quot;1&quot;,<br>                &quot;comment&quot;: &quot;Comment 2 of video 1&quot;,<br>                &quot;user_id&quot;: 1,<br>                &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>                &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;<br>            }<br>        ]<br>    },<br>    {<br>        &quot;id&quot;: 2,<br>        &quot;title&quot;: &quot;Video 2&quot;,<br>        &quot;url&quot;: &quot;https://example.com/video2&quot;,<br>        &quot;user_id&quot;: 2,<br>        &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>        &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>        &quot;comments&quot;: [<br>            {<br>                &quot;id&quot;: 7,<br>                &quot;commentable_type&quot;: &quot;App\\Models\\Video&quot;,<br>                &quot;commentable_id&quot;: &quot;2&quot;,<br>                &quot;comment&quot;: &quot;Comment 1 of video 2&quot;,<br>                &quot;user_id&quot;: 1,<br>                &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>                &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;<br>            },<br>            {<br>                &quot;id&quot;: 8,<br>                &quot;commentable_type&quot;: &quot;App\\Models\\Video&quot;,<br>                &quot;commentable_id&quot;: &quot;2&quot;,<br>                &quot;comment&quot;: &quot;Comment 2 of video 2&quot;,<br>                &quot;user_id&quot;: 2,<br>                &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>                &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;<br>            }<br>        ]<br>    }<br>]</pre><p><strong>5. Fetching Comments and Linking Back to Their Source (Article or Video)</strong></p><p>Now let’s reverse it — instead of fetching an article and getting its comments, let’s fetch a comment and ask it, “Who sent you?!”</p><pre>// CommentController.php<br>public function index()<br>{<br>    $comments = Comment::with(&#39;commentable&#39;)-&gt;get();<br>    return response()-&gt;json($comments);<br>}<br><br>// web.php<br>Route::get(&#39;/comments&#39;, [CommentController::class, &#39;index&#39;]);</pre><p>The result? Each comment brings along its parent, like a kid saying “my mom said I could”. but I cut out a few (marked with …), if I copied them all, it would be as long as my story with her 🤣</p><pre>[<br>    {<br>        &quot;id&quot;: 1,<br>        &quot;commentable_type&quot;: &quot;App\\Models\\Article&quot;,<br>        &quot;commentable_id&quot;: &quot;1&quot;,<br>        &quot;comment&quot;: &quot;Comment 1 of article 1&quot;,<br>        &quot;user_id&quot;: 1,<br>        &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>        &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>        &quot;commentable&quot;: {<br>            &quot;id&quot;: 1,<br>            &quot;title&quot;: &quot;Article 1&quot;,<br>            &quot;body&quot;: &quot;Content of article 1&quot;,<br>            &quot;user_id&quot;: 2,<br>            &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>            &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;<br>        }<br>    },<br>    {<br>        &quot;id&quot;: 2,<br>        &quot;commentable_type&quot;: &quot;App\\Models\\Article&quot;,<br>        &quot;commentable_id&quot;: &quot;1&quot;,<br>        &quot;comment&quot;: &quot;Comment 2 of article 1&quot;,<br>        &quot;user_id&quot;: 2,<br>        &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>        &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>        &quot;commentable&quot;: {<br>            &quot;id&quot;: 1,<br>            &quot;title&quot;: &quot;Article 1&quot;,<br>            &quot;body&quot;: &quot;Content of article 1&quot;,<br>            &quot;user_id&quot;: 2,<br>            &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>            &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;<br>        }<br>    },<br>    ...<br>    {<br>        &quot;id&quot;: 7,<br>        &quot;commentable_type&quot;: &quot;App\\Models\\Video&quot;,<br>        &quot;commentable_id&quot;: &quot;2&quot;,<br>        &quot;comment&quot;: &quot;Comment 1 of video 2&quot;,<br>        &quot;user_id&quot;: 1,<br>        &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>        &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>        &quot;commentable&quot;: {<br>            &quot;id&quot;: 2,<br>            &quot;title&quot;: &quot;Video 2&quot;,<br>            &quot;url&quot;: &quot;https://example.com/video2&quot;,<br>            &quot;user_id&quot;: 2,<br>            &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>            &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;<br>        }<br>    },<br>    {<br>        &quot;id&quot;: 8,<br>        &quot;commentable_type&quot;: &quot;App\\Models\\Video&quot;,<br>        &quot;commentable_id&quot;: &quot;2&quot;,<br>        &quot;comment&quot;: &quot;Comment 2 of video 2&quot;,<br>        &quot;user_id&quot;: 2,<br>        &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>        &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>        &quot;commentable&quot;: {<br>            &quot;id&quot;: 2,<br>            &quot;title&quot;: &quot;Video 2&quot;,<br>            &quot;url&quot;: &quot;https://example.com/video2&quot;,<br>            &quot;user_id&quot;: 2,<br>            &quot;created_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;,<br>            &quot;updated_at&quot;: &quot;2025-04-24T15:42:59.000000Z&quot;<br>        }<br>    }<br>]</pre><h3>And That’s a Wrap!</h3><p>Cool, right? Almost magical. With polymorphic relationships, you can link one model to many other models the same way — no need to create a separate comments table for every type of content. Just one comment table to rule them all.</p><p>So instead of spending time building extra tables, you can focus on more critical features — like, you know, that “ex-stalker mode” feature (kidding… 😅).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aff5fca35fb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boost Your Laravel Skills: Simplify Code with Blade Helpers]]></title>
            <link>https://ferdyhape.medium.com/boost-your-laravel-skills-simplify-code-with-blade-helpers-96a850023e7f?source=rss-73ca9457d692------2</link>
            <guid isPermaLink="false">https://medium.com/p/96a850023e7f</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[code-optimization]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[dry-programming]]></category>
            <dc:creator><![CDATA[Ferdy Hahan Pradana]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 17:12:54 GMT</pubDate>
            <atom:updated>2025-04-23T17:15:21.677Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EyPyBcTJvESzSvj1emVgxA.png" /></figure><h3>I thought repeating myself was harmless — until I had to update the same code in five different files.</h3><p>At first, copy-pasting code in Blade views feels like a quick fix. But over time, it can turn into a bit of a headache.</p><p>This is where Blade helpers can help — small, reusable functions that keep your templates neat and save you from repeating yourself too much. Let me show you how using just one helper can make your life easier.</p><h3>Case</h3><p>Let’s say you have some data like this:</p><pre>[<br>    {<br>        &quot;id&quot;: 1,<br>        &quot;name&quot;: &quot;Mechanical Keyboard&quot;,<br>        &quot;description&quot;: &quot;Keyboard with RGB key switches that are highly responsive and comfortable for gaming.&quot;,<br>        &quot;code&quot;: &quot;KB001&quot;,<br>        &quot;price&quot;: &quot;350000&quot;,<br>        &quot;created_at&quot;: &quot;2025-04-23T15:30:10.000000Z&quot;,<br>        &quot;updated_at&quot;: &quot;2025-04-23T15:30:10.000000Z&quot;<br>    },<br>    {<br>        &quot;id&quot;: 2,<br>        &quot;name&quot;: &quot;Wireless Mouse&quot;,<br>        &quot;description&quot;: &quot;Ergonomic wireless mouse with a slim design that is very comfortable for daily use.&quot;,<br>        &quot;code&quot;: &quot;MS001&quot;,<br>        &quot;price&quot;: &quot;150000&quot;,<br>        &quot;created_at&quot;: &quot;2025-04-23T15:30:10.000000Z&quot;,<br>        &quot;updated_at&quot;: &quot;2025-04-23T15:30:10.000000Z&quot;<br>    }<br>]</pre><p>For your UI list, you’ll need to limit the description to, say, 50 characters. Seems simple, right?</p><p>Here’s how you could handle it:</p><pre>// resources/views/admin/products/index.blade.php<br><br>function limit_characters($string, $limit = 50)<br>{<br>    return strlen($string) &gt; $limit ? substr($string, 0, $limit) . &#39;...&#39; : $string;<br>}<br><br>...<br><br> @foreach ($products as $product)<br>    &lt;tr&gt;<br>        &lt;td&gt;{{ $loop-&gt;iteration }}&lt;/td&gt;<br>        &lt;td&gt;{{ $product-&gt;name }}&lt;/td&gt;<br>        &lt;td&gt;{{ limit_characters($product-&gt;description, 50) }}&lt;/td&gt;<br>        &lt;td&gt;{{ $product-&gt;price }}&lt;/td&gt;<br>        &lt;td class=&quot;text-center&quot;&gt;<br>            &lt;button class=&quot;btn btn-primary btn-sm&quot;&gt;Edit&lt;/button&gt;<br>            &lt;button class=&quot;btn btn-danger btn-sm&quot;&gt;Delete&lt;/button&gt;<br>        &lt;/td&gt;<br>    &lt;/tr&gt;<br>@endforeach</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dE5cB2TC96n7SlnfVuqYbg.png" /><figcaption>Product Table Example</figcaption></figure><p>But hold on — what if you need to use that character limit in multiple places? You’d be stuck copying the same function across different files. After finishing admin/products/index.blade.php, you find yourself pasting limit_characters into frontend/products/index.blade.php, like this:</p><pre>// resources/views/frontend/products/index.blade.php<br>function limit_characters($string, $limit = 50)<br>{<br>    return strlen($string) &gt; $limit ? substr($string, 0, $limit) . &#39;...&#39; : $string;<br>}<br><br>...<br><br>@foreach ($products as $product)<br>    &lt;div class=&quot;col&quot;&gt;<br>        &lt;div class=&quot;card shadow border-light rounded-3&quot;&gt;<br>            &lt;div class=&quot;card-body&quot;&gt;<br>                &lt;h5 class=&quot;card-title text-truncate&quot; style=&quot;max-width: 100%&quot;&gt;{{ $product-&gt;name }}&lt;/h5&gt;<br>                &lt;p class=&quot;card-text text-truncate&quot; style=&quot;max-width: 100%&quot;&gt;<br>                    {{ limit_characters($product-&gt;description, 50) }}&lt;/p&gt;<br>                &lt;div class=&quot;d-flex justify-content-between align-items-center&quot;&gt;<br>                    &lt;span class=&quot;badge bg-primary text-white p-2&quot;&gt;${{ $product-&gt;price }}&lt;/span&gt;<br>                    &lt;a href=&quot;#&quot; class=&quot;btn btn-sm btn-outline-primary&quot;&gt;<br>                        Check<br>                    &lt;/a&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>@endforeach</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0B5WRyAakIszItN6J0Nrdg.png" /><figcaption>Product Card Example</figcaption></figure><p>I really hope you’re not doing that! We’re talking about <strong>DRY (Don’t Repeat Yourself)</strong> here. Copy-pasting the same function everywhere just creates duplicate code. And when you need to update it later, you’ll be updating every single file. Imagine spending your whole afternoon in a coffee shop doing that instead of enjoying a good chat. Not the best use of your time, right?</p><h3>So, What’s Next?</h3><p>Here’s the solution: let’s create a Blade Helper that allows us to write cleaner, reusable code. By using a Blade Helper, we can avoid the redundancy of writing the same code over and over again across different parts of our application.</p><h3>Step-by-Step Guide:</h3><p><strong>1. Create the Blade Helper File:</strong> First, create a new file inside the app/Helpers folder (if the folder doesn’t exist, create it) and name it something likeBladeHelper.php.</p><p><strong>2. Define the Function:</strong> Inside that file, we’ll define the function we will use in the Blade templates.</p><pre>// app/Helpers/BladeHelper.php<br>&lt;?php<br><br>if (!function_exists(&#39;limit_characters&#39;)) {<br>    function limit_characters($string, $limit = 50)<br>    {<br>        return strlen($string) &gt; $limit ? substr($string, 0, $limit) . &#39;...&#39; : $string;<br>    }<br>}</pre><p><strong>3. Register the Helper in Composer:</strong> To let Laravel recognize our helper, we need to register it in the composer.json file. Open the composer.json file and add the path to our helper in the autoload section (if the files key doesn’t exist under autoload, you can add it yourself).</p><pre>{<br>    &quot;autoload&quot;: {<br>        &quot;files&quot;: [&quot;app/Helpers/BladeHelper.php&quot;]<br>    }<br>}</pre><p><strong>4. Run Composer Dump-Autoload:</strong> After adding the path to the helper, run the following command in the terminal to update the autoloading:</p><pre>composer dump-autoload</pre><p>Now, we’ve created the helper and registered it. We can now use the limit_characters function anywhere in our Blade templates without having to define it again.</p><pre>// resources/views/admin/products/index.blade.php<br>@foreach ($products as $product)<br>    &lt;tr&gt;<br>        &lt;td&gt;{{ $loop-&gt;iteration }}&lt;/td&gt;<br>        &lt;td&gt;{{ $product-&gt;name }}&lt;/td&gt;<br>        &lt;td&gt;{{ limit_characters($product-&gt;description, 50) }}&lt;/td&gt;<br>        &lt;td&gt;{{ $product-&gt;price }}&lt;/td&gt;<br>        &lt;td class=&quot;text-center&quot;&gt;<br>            &lt;button class=&quot;btn btn-primary btn-sm&quot;&gt;Edit&lt;/button&gt;<br>            &lt;button class=&quot;btn btn-danger btn-sm&quot;&gt;Delete&lt;/button&gt;<br>        &lt;/td&gt;<br>    &lt;/tr&gt;<br>@endforeach<br><br>// resources/views/frontend/products/index.blade.php<br>@foreach ($products as $product)<br>    &lt;div class=&quot;col&quot;&gt;<br>        &lt;div class=&quot;card shadow border-light rounded-3&quot;&gt;<br>            &lt;div class=&quot;card-body&quot;&gt;<br>                &lt;h5 class=&quot;card-title text-truncate&quot; style=&quot;max-width: 100%&quot;&gt;{{ $product-&gt;name }}&lt;/h5&gt;<br>                &lt;p class=&quot;card-text text-truncate&quot; style=&quot;max-width: 100%&quot;&gt;<br>                    {{ limit_characters($product-&gt;description, 50) }}&lt;/p&gt;<br>                &lt;div class=&quot;d-flex justify-content-between align-items-center&quot;&gt;<br>                    &lt;span class=&quot;badge bg-primary text-white p-2&quot;&gt;${{ $product-&gt;price }}&lt;/span&gt;<br>                    &lt;a href=&quot;#&quot; class=&quot;btn btn-sm btn-outline-primary&quot;&gt;<br>                        Check<br>                    &lt;/a&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>@endforeach</pre><h3>The Bottom Line</h3><p>In a nutshell, using Blade Helpers means no more redundant code and a lot more free time for coffee breaks. Who doesn’t want that? Keep it DRY and enjoy the process!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96a850023e7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing OOP with Laravel Traits: A Practical Relationship Guide]]></title>
            <link>https://ferdyhape.medium.com/optimizing-oop-with-laravel-traits-a-practical-relationship-guide-2d4999dbea06?source=rss-73ca9457d692------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d4999dbea06</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <dc:creator><![CDATA[Ferdy Hahan Pradana]]></dc:creator>
            <pubDate>Wed, 02 Oct 2024 18:02:54 GMT</pubDate>
            <atom:updated>2024-10-02T18:02:54.574Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wQkq1Ctt_Ffpc4aQATpouQ.png" /></figure><h3>Case Study</h3><p>Imagine you’ve got a bunch of models like `Post`, `Comment`, and `Like`, and each of them needs to relate to a `User`. Writing the same relationship code again and again can be pretty annoying, right? 😩</p><h4><strong>Example Without Traits</strong></h4><pre>// Post.php<br>public function user()<br>{<br>    return $this-&gt;belongsTo(User::class);<br>}<br>// Comment.php<br>public function user()<br>{<br>  return $this-&gt;belongsTo(User::class);<br>}<br>// Like.php<br>public function user()<br>{<br>  return $this-&gt;belongsTo(User::class);<br>}</pre><p>This repetition can become cumbersome, especially if you need to maintain consistency across many models. 😩</p><h4><strong>Example With Traits</strong></h4><p>Wouldn’t it be better if you could refactor this into a trait and reuse the relationship logic? 😍</p><pre>// Post.php<br>use HasUser;<br>// Comment.php<br>use HasUser;<br>// Like.php<br>use HasUser;</pre><p>Cleaner, right? Now, let’s break down how to implement this for better maintainability and readability.</p><h3>Step-by-Step Guide</h3><h4><strong>Create a Custom Command to Generate Traits (For Laravel Versions Below 11)</strong></h4><p>If you’re using Laravel under version 11, you can create a command to generate the trait. Run this command:</p><pre>php artisan make:command CreateTraitCommand</pre><p>Then, open the generated file in <em>app/Console/Commands/CreateTraitCommand.php</em> and add edit the code like this:</p><pre>&lt;?php<br>namespace App\Console\Commands;<br>   use Illuminate\Console\Command;<br>   use Illuminate\Support\Facades\File;<br>   class CreateTraitCommand extends Command<br>   {<br>       <br>       protected $signature = &#39;make:trait {name}&#39;;<br>       protected $description = &#39;Create a new trait&#39;;<br>       public function handle()<br>       {<br>           $name = $this-&gt;argument(&#39;name&#39;);<br>           $traitPath = app_path(&quot;Traits/{$name}.php&quot;);<br>           // Cek apakah trait sudah ada<br>           if (File::exists($traitPath)) {<br>               $this-&gt;error(&quot;Trait {$name} already exists!&quot;);<br>               return;<br>           }<br>           // Membuat direktori jika belum ada<br>           if (!File::exists(app_path(&#39;Traits&#39;))) {<br>               File::makeDirectory(app_path(&#39;Traits&#39;));<br>           }<br>           // Template isi trait<br>           $traitTemplate = &quot;&lt;?php<br>   namespace App\Traits;<br>   trait $name<br>   {<br>       // Add your methods here<br>   }<br>   &quot;;<br>           // Menulis file trait baru<br>           File::put($traitPath, $traitTemplate);<br>           $this-&gt;info(&quot;Trait {$name} created successfully.&quot;);<br>       }<br>   }</pre><h4><strong>Create Trait</strong></h4><p>Run this command to create a trait:</p><pre>php artisan make:trait HasUser</pre><p>Then, open the generated file in <em>app/Traits/HasUser.php</em> and add the relationship code like this:</p><pre>&lt;?php<br><br>namespace App\Traits;<br><br>trait HasUser<br>{<br>    public function user()<br>    {<br>        return $this-&gt;belongsTo(User::class);<br>    }<br>}</pre><h4>Use Trait in Model</h4><p>Use the trait in your model like this:</p><pre>// Post.php<br><br>&lt;?php<br><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Model;<br><br>class Post extends Model<br>{<br>    use HasUser;<br>}</pre><p>and so on for other models like `Comment` and `Like`, and you’re good to go! 😎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d4999dbea06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blockchain for Beginners: Build Your Own Private Ethereum Network with Geth (Step by step)]]></title>
            <link>https://ferdyhape.medium.com/blockchain-for-beginners-build-your-own-private-ethereum-network-with-geth-step-by-step-311342370fec?source=rss-73ca9457d692------2</link>
            <guid isPermaLink="false">https://medium.com/p/311342370fec</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[geth]]></category>
            <category><![CDATA[private-blockchain]]></category>
            <category><![CDATA[smart-contract-blockchain]]></category>
            <category><![CDATA[go-ethereum]]></category>
            <dc:creator><![CDATA[Ferdy Hahan Pradana]]></dc:creator>
            <pubDate>Sat, 27 Apr 2024 20:03:14 GMT</pubDate>
            <atom:updated>2024-04-27T20:03:14.149Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WsSBjhs2sFXLKutRuEinCA.png" /></figure><h3>Description</h3><p>Are you ready to move beyond development tools? After I shared <a href="https://ferdyhape.medium.com/remix-ide-and-ganache-a-beginners-guide-to-smart-contract-deployment-b0df68c48ae6">how to deploy smart contracts using ganache and remix</a>, this time, we’ll build a private Ethereum network with Geth! This handy guide will get you started, perfect for beginners who want to experiment with blockchain technology.</p><h3>Information of the device used</h3><p>In this article, I am using <strong><em>Ubuntu 22.04.3</em></strong> LTS for my OS, if you are using another linux distro, or using windows or mac, I think there is no problem but you have to adjust for installation prerequisites</p><h3>Prerequisites</h3><ul><li><a href="https://go.dev/doc/install">Go Language</a> (in this article, I am using go version 1.22.0)</li><li><a href="https://geth.ethereum.org/docs/getting-started/installing-geth">Go Ethereum</a> (in this article, I am using geth version 1.13.14-stable)</li><li>VSCode (this is optional, you can use your favorite code editor)</li></ul><h3>The steps are as follows:</h3><h4>Make project folder</h4><p>in the first step, we will create a project folder that will be used to create a blockchain network</p><pre>mkdir geth-tutorial</pre><p>Navigate to your project folder using the command line.</p><pre>cd geth-tutorial</pre><h4>Creating nodes</h4><p>In this step, we’ll set up separate folders for each node in our blockchain network. Let’s create folders named “node1” and “node2” to represent our network nodes.</p><pre>mkdir node1 node2</pre><h4>Managing Node Information</h4><p>after each node1 and node2 folder is created, we will create an info.txt file in the root of our project folder to store information such as account addresses and passwords for node1 and node2. This will help us keep track of important details related to our nodes.</p><pre>touch info.txt</pre><h4>Open Code Editor (optional, for easy viewing)</h4><p>In this step, iam using VS Code</p><pre>code .</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oXMJ6R94y59ZoGgG" /></figure><h4>Creating Accounts for Node1 and Node2</h4><p>Next we will create accounts for node1 and node2. We will open a separate terminal for each node folder and run the command as below</p><pre>geth --datadir &quot;./data&quot; account new</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A4PdJYd4LQEpu8qW" /></figure><h4>Verifying Account Creation</h4><p>To ensure that the accounts for node1 and node2 have been successfully created, we will check the keystore folder inside each node’s data directory.</p><ol><li>Open the keystore folder in the data directory of node1 and node2.</li><li>Verify that new account files are present within each keystore folder.</li></ol><p>By confirming the presence of account files, we can ensure that the accounts for node1 and node2 have been successfully created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/0*wwa6esrB0GgVpazX" /></figure><h4>Saving Account Information</h4><p>for the accounts created earlier, we’ll save the public addresses and passwords for the accounts created for node1 and node2 to the info.txt file.</p><ol><li>Open the info.txt file located at the root of the project folder.</li><li>Add the public address and password for each account created for node1 and node2.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3twepOqf-lPS4v87" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/0*anZzobq9PtGR6_M9" /></figure><h4>Creating Configuration File</h4><p>In this step, the account has been created, next we will create a file called “privateblock.json” for configuration in the root directory of the project. Then, we will copy and paste the script provided below into the “privateblock.json” file.</p><ol><li>Create a file named “privateblock.json” in the root directory of your project.</li><li>Copy and paste the following script into “privateblock.json”:</li></ol><pre>{<br>  &quot;config&quot;: {<br>    &quot;chainId&quot;: 1234567,<br>    &quot;homesteadBlock&quot;: 0,<br>    &quot;eip150Block&quot;: 0,<br>    &quot;eip155Block&quot;: 0,<br>    &quot;eip158Block&quot;: 0,<br>    &quot;byzantiumBlock&quot;: 0,<br>    &quot;constantinopleBlock&quot;: 0,<br>    &quot;petersburgBlock&quot;: 0,<br>    &quot;istanbulBlock&quot;: 0,<br>    &quot;berlinBlock&quot;: 0,<br>    &quot;clique&quot;: {<br>      &quot;period&quot;: 5,<br>      &quot;epoch&quot;: 30000<br>    }<br>  },<br>  &quot;difficulty&quot;: &quot;1&quot;,<br>  &quot;gasLimit&quot;: &quot;8000000&quot;,<br>  &quot;extradata&quot;: &quot;0x0000000000000000000000000000000000000000000000000000000000000000{ INITIAL_SIGNER_ADDRESS }0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000&quot;,<br>  &quot;alloc&quot;: {<br>    &quot;{ FIRST_NODE_ADDRESS }&quot;: {<br>      &quot;balance&quot;: &quot;3000000000000000000000000000000000000&quot;<br>    },<br>    &quot;{ SECOND_NODE_ADDRESS }&quot;: {<br>      &quot;balance&quot;: &quot;3000000000000000000000000000000000000&quot;<br>    }<br>  }<br>}</pre><p>3. Replace “{ FIRST_NODE_ADDRESS }” to the public address for each node account and change “{ INITIAL_SIGNER_ADDRESS }” to one of the node’s public addresses (remove the leading “0x” character).<br>for example, these are my accounts for each node</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*jIc1X-AfxO5Ng_UbP-W3DA.png" /></figure><p>and, this is my script in privateblock.json</p><pre>{<br>    &quot;config&quot;: {<br>        &quot;chainId&quot;: 1234567,<br>        &quot;homesteadBlock&quot;: 0,<br>        &quot;eip150Block&quot;: 0,<br>        &quot;eip155Block&quot;: 0,<br>        &quot;eip158Block&quot;: 0,<br>        &quot;byzantiumBlock&quot;: 0,<br>        &quot;constantinopleBlock&quot;: 0,<br>        &quot;petersburgBlock&quot;: 0,<br>        &quot;istanbulBlock&quot;: 0,<br>        &quot;berlinBlock&quot;: 0,<br>        &quot;clique&quot;: {<br>            &quot;period&quot;: 5,<br>            &quot;epoch&quot;: 30000<br>        }<br>    },<br>    &quot;difficulty&quot;: &quot;1&quot;,<br>    &quot;gasLimit&quot;: &quot;8000000&quot;,<br>    &quot;extradata&quot;: &quot;0x0000000000000000000000000000000000000000000000000000000000000000A43ffF7C765A30f797C7F0108291958faA30Fa170000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000&quot;,<br>    &quot;alloc&quot;: {<br>        &quot;A43ffF7C765A30f797C7F0108291958faA30Fa17&quot;: {<br>            &quot;balance&quot;: &quot;3000000000000000000000000000000000000&quot;<br>        },<br>        &quot;5b5cD226194D0EDe2652102D52Fc0A9ed0F38C0D&quot;: {<br>            &quot;balance&quot;: &quot;3000000000000000000000000000000000000&quot;<br>        }<br>    }<br>}</pre><h4>Initializing Nodes</h4><p>Account and configuration have been created, it’s time we initialize each node with the configuration that has been created using the following command:</p><pre>geth --datadir ./data init ../privateblock.json</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CExhKguoTW9JXW9x" /></figure><h4>Setting Up Bootnode</h4><p>In this step, we’ll create a folder named “bnode” in the root of our project directory to set up the bootnode. The bootnode acts as a central hub for node discovery in the Ethereum network. It generates unique enode URLs and facilitates the connection of new nodes, enabling network synchronization and decentralized communication.</p><p>Create a folder named “bnode” in the root directory of your project.</p><pre>mkdir bnode<br>cd bnode</pre><h4>Generating Bootnode Key and Running Bootnode</h4><p>Next we’ll generate the bootnode key and run the bootnode.</p><ol><li>Generate the bootnode key in the “bnode” folder:\</li></ol><pre>bootnode -genkey boot.key</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*jeMtPJ4YIKpIdaky" /></figure><p>2. After generating the key, run the bootnode with the following command:</p><pre>bootnode -nodekey boot.key -verbosity 7 -addr &quot;127.0.0.1:30301&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xv1K_hz67U1PIjXq" /></figure><h4>Storing Bootnode Enode</h4><p>To make things easier, we will store the enode information for the bootnode in the “info.txt” file in the root project folder.</p><ol><li>Open the “info.txt” file located at the root of the project directory.</li><li>Add the enode information for the bootnode:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*66MMBpOkBb6VyJP0" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sVwgZskOaFIzjo0L" /></figure><h4>Storing Passwords</h4><p>Coming to one step before we run each of the nodes, we will create a file called “password.txt” inside the node1 and node2 folders and enter the password for each node in the respective file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QKeKIV249CMqEcyi" /></figure><h4>Starting Signer Account (Node1)</h4><p>Okay, now we will run the script to start a signer account using node1. We will customize the script with appropriate parameters such as enode, network ID (chainId), signer node address, password, and signer address.</p><pre>geth --datadir &quot;./data&quot;  --port 30304 --bootnodes enode://{ YOUR_VALUE } --authrpc.port 8547 --ipcdisable --allow-insecure-unlock  --http --http.corsdomain=&quot;https://remix.ethereum.org&quot; --http.api web3,eth,debug,personal,net --networkid { NETWORK_ID } --unlock { ADDRESS_NODE1 } --password { PASSWORD_FILE_NAME_EXTENSION }  --mine --miner.etherbase= { SIGNER_ADDRESS }</pre><p>For example, This is my script</p><pre>geth - datadir &quot;./data&quot; - port 30304 - bootnodes enode://7c8ae5080a4e655b82868853abf24164dc62a13f16118ae0e9a6d6446fa5013e7e7809912474057836628804837380549d680b29f26b350c1350dad385e2b538@127.0.0.1:0?discport=30301 - authrpc.port 8547 - ipcdisable - allow-insecure-unlock - http - http.corsdomain=&quot;https://remix.ethereum.org&quot; - http.api web3,eth,debug,personal,net - networkid 1234567 - unlock 0xA43ffF7C765A30f797C7F0108291958faA30Fa17 - password password.txt - mine - miner.etherbase=0xA43ffF7C765A30f797C7F0108291958faA30Fa17</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AfEKVa7LG90ZNxwo" /></figure><p><strong>Notes:</strong></p><p><strong>for set cors allow for “</strong><a href="http://127.0.0.1:8000/"><strong>http://127.0.0.1:8000</strong></a><strong>”, add “</strong><a href="http://127.0.0.1:8000/"><strong>http://127.0.0.1:8000</strong></a><strong>” to “ — http.corsdomain”</strong></p><p>example:</p><pre>geth --datadir &quot;./data&quot;  --port 30304 --bootnodes enode://7c8ae5080a4e655b82868853abf24164dc62a13f16118ae0e9a6d6446fa5013e7e7809912474057836628804837380549d680b29f26b350c1350dad385e2b538@127.0.0.1:0?discport=30301 --authrpc.port 8547 --ipcdisable --allow-insecure-unlock  --http --http.corsdomain=&quot;https://remix.ethereum.org, http://127.0.0.1:8000&quot; --http.api web3,eth,debug,personal,net --networkid 1234567 --unlock 0xA43ffF7C765A30f797C7F0108291958faA30Fa17 --password password.txt  --mine --miner.etherbase=0xA43ffF7C765A30f797C7F0108291958faA30Fa17</pre><h4>Running Other Nodes</h4><p>Then, how to run nodes other than the signer node? we can run nodes other than the signer node (node1) using script command below</p><pre>geth --datadir &quot;./data&quot;  --port 30306 --bootnodes enode://{ YOUR_VALUE }  -authrpc.port 8546 --networkid { NETWORK_ID } --unlock { ADDRESS_NODE2 } --password { PASSWORD_FILE_WITH_EXTENSION }</pre><p>and this example of my script for running node2</p><pre>geth --datadir &quot;./data&quot;  --port 30306 --bootnodes enode://7c8ae5080a4e655b82868853abf24164dc62a13f16118ae0e9a6d6446fa5013e7e7809912474057836628804837380549d680b29f26b350c1350dad385e2b538@127.0.0.1:0?discport=30301  -authrpc.port 8546 --networkid 1234567 --unlock 0x5b5cD226194D0EDe2652102D52Fc0A9ed0F38C0D --password password.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/0*YzbnvBielDS2sPb_" /></figure><h4>Deploying Smart Contract</h4><p><strong>Blockchain network has been created</strong>, to check deploy smart contract, try to deploy in <a href="https://remix.ethereum.org/">REMIX IDE</a> with provider “custom — external http provider” with host and port <a href="http://127.0.0.1:8545/">http://127.0.0.1:8545</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/0*rfgjSS_aO4g4Zfz0" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/0*83J-mcpHVxukMzlI" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fHETQkCoaPU9iCU-" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F_qpOFG6dlqKrlLw" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=311342370fec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remix IDE and Ganache: A Beginner’s Guide to Smart Contract Deployment]]></title>
            <link>https://ferdyhape.medium.com/remix-ide-and-ganache-a-beginners-guide-to-smart-contract-deployment-b0df68c48ae6?source=rss-73ca9457d692------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0df68c48ae6</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ganache]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[remix-ide]]></category>
            <dc:creator><![CDATA[Ferdy Hahan Pradana]]></dc:creator>
            <pubDate>Sat, 16 Mar 2024 03:28:16 GMT</pubDate>
            <atom:updated>2024-03-16T03:28:16.741Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1X02Dao6laFLiCQNHY1pQ.png" /></figure><h3>Description</h3><p>After I shared a tutorial on <a href="https://ferdyhape.medium.com/deploy-smart-contract-with-truffle-and-ganache-d0a3af492de9"><strong>deploying smart contracts with Truffle and Ganache</strong></a>, I’m back with another approach! Today, we’ll explore how to deploy smart contracts using Remix IDE and Ganache. Many beginners find Remix IDE to be a more user-friendly option compared to Truffle. <strong>Here, I’m assuming you’re already familiar with Ganache and Remix IDE, so we’ll jump right into the technical execution.</strong> Let’s dive in!</p><h3>Information of the device used</h3><p>In this article, I am using <strong><em>Ubuntu 22.04.3</em></strong> LTS for my OS, if you are using another linux distro, or using windows or mac, I think there is no problem but you have to adjust for installation prerequisites</p><h3>Prerequisites</h3><ul><li>NodeJS (in this article, I am using node version 16.20.2)</li><li>Npm (in this article, I am using node version 8.19.4)</li></ul><h3>The steps are as follows:</h3><h4>Installing ganache</h4><p>In the <a href="https://www.npmjs.com/package/ganache">ganache installation documentation</a>, To install ganache, make sure you have installed <strong>Nodejs &gt;= v16.0.0 and npm &gt;= 7.10.0</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*VwSAkJiE61G8ncrBHvfy2w.png" /><figcaption>for documentaion, you can be found <a href="https://www.npmjs.com/package/ganache">https://www.npmjs.com/package/ganache</a></figcaption></figure><p>If you have met the requirements for npm and nodeJS, <strong>install ganache with open your terminal and execute command below</strong></p><pre>npm install ganache --global</pre><p>to make sure ganache is installed, you can execute the command below to check the ganache version</p><pre>ganache --version</pre><p>if your terminal returns information for the ganache version, it indicates you <strong>successfully</strong> installed ganache</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*1P8sTTtZTHF988Eh0lGX9w.png" /></figure><h4>Go to REMIX IDE</h4><p>now, we will go to REMIX IDE, you can open this link <a href="http://remix.ethereum.org/">http://remix.ethereum.org/</a></p><p>At the start, you will be given information about the REMIX IDE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNqUXCKMnStseIKGZUpoHQ.png" /></figure><p>In the file explorer of REMIX IDE, expand contracts folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*IcdVJXQsQgq5erTQMzwYEw.png" /></figure><p>For example, we will use the default smart contract provided by the REMIX IDE with the name <strong>1_Storage.sol</strong>, click the smart contract with name 1_Storage.sol</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bibBJzRis3GZ7HrruKAEsw.png" /></figure><p>click solidity compiler (<strong>under the search icon</strong>) and <strong>click</strong> “<strong>Compile 1_Storage.sol</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*VI9zTUxTFkIiHLzN2kVbUQ.png" /></figure><p>once the smart contract is successfully compiled, you can see a check mark on the solidity compiler icon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/102/1*dJNCx3Xx0Nnf2Tbbx_uMjw.png" /></figure><p>after finishing compiling, now open the terminal again and type “ganache” to run the ganache server</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*NxBOY9Ddz1kpQ3T3Ylm_pA.png" /></figure><p>The next step is to deploy the smart contract to the ganache server. reopen remix ideas in the browser then <strong>click the “run and deploy transaction”</strong> icon <strong>under the solidity compiler icon</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*6albquanUr4_09oBzAWDxQ.png" /></figure><p>click on the environment dropdown, by default the environment used is “Remix VM (Shanghai)”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*KLPBd_TSH078Jr_kieLvbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*OGAf4On3EIDVO6wpdN1vVA.png" /></figure><p>change the environment to “Dev-Ganache Provider”, and use the default hostname with port “<a href="http://127.0.0.1:8545/">http://127.0.0.1:8545</a>”, then clik OK</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*1GnanCu3QPCli5ZH_HaWLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*nAyH6tkT2xTUVLG97vr-kQ.png" /></figure><p>if you have successfully connected to the ganache server, then click the deploy button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*LCzdyHl32VoUP7qifvBWeQ.png" /></figure><p>yass, <strong>now we successfully deployed the smart contract</strong>, look at the bottom of menu deploy &amp; run transaction and terminal on the REMIX IDE, there is a description of the smart contract successfully deployed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*B-4evwqFPkSscnv-gzjf-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*F5x-IpjlN30OkTX6rD41oQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*h_WFdko9xaO3OwHuhbDadg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ImxeQsSrh8FNNOXon4wwUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JgHnAhd0rH0rN5fAooXMRw.png" /></figure><p>You can also see in the terminal where the ganache server is running, there is also a statement that the smart contract has been created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*c_hsycxrIQizVSo5uYQ5sA.png" /></figure><h3>Conclusion</h3><p>In this guide, we explored deploying smart contracts using Remix IDE and Ganache. We learned that Remix IDE offers a beginner-friendly alternative for smart contract deployment. We covered installing Ganache, connecting Remix IDE to the Ganache server, and finally deploying a sample smart contract provided by REMIX IDE. With these steps, you’re ready to deploy your own smart contracts on a local blockchain network!</p><p><strong>In my opinion, deploying smart contracts with Remix IDE and Ganache is generally considered a simpler and easier process compared to using Truffle.</strong> This is because Remix IDE provides a user-friendly interface and eliminates the need for additional configuration and setup steps required with Truffle.</p><p>Happy Explore!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0df68c48ae6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to Smart Contract Deployment with Truffle and Ganache]]></title>
            <link>https://ferdyhape.medium.com/deploy-smart-contract-with-truffle-and-ganache-d0a3af492de9?source=rss-73ca9457d692------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0a3af492de9</guid>
            <category><![CDATA[truffle-suite]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ganache]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Ferdy Hahan Pradana]]></dc:creator>
            <pubDate>Fri, 15 Mar 2024 16:22:59 GMT</pubDate>
            <atom:updated>2024-03-15T17:44:33.975Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Solidity to Blockchain: A Beginner’s Guide to Smart Contract Deployment with Truffle and Ganache</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*mMXJ9UBFh1bm3c_1dWRGiw.png" /><figcaption>source of image: <a href="https://news.cryptoizresearch.com/wp-content/uploads/2020/10/1_82A3uvAKYw-RTo99FyfxyQ.png">https://news.cryptoizresearch.com/wp-content/uploads/2020/10/1_82A3uvAKYw-RTo99FyfxyQ.png</a></figcaption></figure><h3>Description:</h3><p>Embark on your journey from Solidity code to the blockchain realm with our beginner-friendly guide to deploying smart contracts using Truffle and Ganache. This comprehensive tutorial walks you through each step, demystifying the process and empowering you to bring your decentralized applications to life seamlessly.</p><h3>Description of the device used</h3><ul><li>Ubuntu 22.04.3 LTS</li></ul><h3>Requirements used on the device:</h3><ul><li>Truffle v5.11.5 (core: 5.11.5)</li><li>Ganache v7.9.1</li><li>Solidity — 0.8.21 (solc-js)</li><li>Node v16.20.2</li><li>Web3.js v1.10.0</li></ul><h3>The steps are as follows:</h3><h4>Create a new folder for the project and open it in visual studio code</h4><p>This folder will be created for the truffle project that will be created.</p><pre>mkdir project-name<br>cd project-name<br>code .</pre><h4>Download the truffle extension for VS Code</h4><p>to make the process easier, download and use the “Truffle for VSCode” extension, you can download directly at vscode or at the link <a href="https://marketplace.visualstudio.com/items?itemName=trufflesuite-csi.truffle-vscode">here</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/0*aC3fdDzu6IXwq6xT" /></figure><h4>Download and customize the requirements based on what is listed on the startup extension</h4><p>After you install it, you will be shown some related software installation requirements for some future processes. So, you can customize the related software needs before proceeding to the next process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rv102DXPhwVyJ1w4" /></figure><h4>Create a new network for the ganache server</h4><p>If everything is installed, the next process is to create a ganache server to deploy the smart contract later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/0*kqHYAyb2R_1bk5CP" /></figure><p>In this process I followed the default advice to create a new network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/0*C9fgi1F4-kBqmyOn" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/0*G1Xo8kZtHjDXbPXN" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/0*iEbtpN67Rb0PlZB3" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/0*mGrECGAdIvkN0nt4" /></figure><h4>Start the network</h4><p>if the network has been created, start it by right-clicking the network name, then click start ganache</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/0*d0e0r_rbmAjEj97A" /></figure><p>You can see that the ganache server has started with the check in output (left side of the terminal in vscode)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*njWFFoVLn_qpnZrz" /></figure><h4>Initiate truffle project</h4><p>to start the truffle project, you can open a terminal in vscode and run the command below</p><pre>truffle init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/0*dcGkJJOplWqEQc55" /></figure><p>after running the command, look in vscode explorer, you can see some folders and files, including truffle-config.js has been created automatically, this is a set of truffle project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/0*eTeQLCq4enYN_t0X" /></figure><h4>Create a smart contract</h4><p>next process, you can create a smart contract with the execute command below, change “<strong>contractName</strong>” with your contract name</p><pre>truffle create contract contractName</pre><p>here iam create 2 contract with name TransactionContract and TransactionDetailContract</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/0*xsjaBPU5Qp08F-TP" /></figure><p>after the command is executed, look at the “<strong>contracts</strong>” folder, you can see a new smart contract with the extension name .sol has been created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/0*5iSmSsB-olz9vj7O" /></figure><p>Okay, now customize the smart contract that was just created as needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1H-WuxsXVUJIFDiQ" /></figure><h4>Network configuration in the truffle-config.js file</h4><p>Next, set the network configuration in truffle-config.js so that it can connect to the ganache server that was run earlier</p><p><strong>Note</strong>: customize the port, hostname like the previously created ganache server</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/0*zr5D3Mlp2xcsgQnf" /></figure><h4>Create a new migration</h4><p>create a new migration to deploy to the ganache server by executing the command below, replace “migrationName” with the name of the migration to be created.</p><pre>truffle create migration migrationName</pre><p>because earlier I created 2 smart contracts, then here I create 2 migrations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*LttfucNy1bRSPNBD" /></figure><p>after the command is executed, it will create a new file in the “migration” folder, this is the migration file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/0*qdcRYxxJ3s-o4b82" /></figure><p>Open it completely and adjust it to the needs of the smart contract that will be deployed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3UoOjg5pXEZfxwYbk6DEzg.png" /></figure><h4>Run the migration</h4><p>After the migration file has been adjusted, the next process is to run the migration for the smart contract deployment process by executing the command below.</p><pre>truffle migrate</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/0*iSLA399hHO8EFF0s" /></figure><h4>Smart contract successfully deployed</h4><p>done, the smart contract was successfully deployed on the ganache server, to see the contract address you can see it in the terminal at “<strong>contract address</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*qG3X4c9WzfZSuafv" /></figure><p>If the terminal has been cleared, it can be seen in ./build/contracts, find the word “address”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/0*gJpZsjPHiymFy1rR" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/0*-k9kOQw8dhi2yk2J" /></figure><p>and if you want to monitor activity on the ganache server that has been running, can be checked in the output on the left side of the terminal on vscode</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3IiTMD3tXvRbtjOP" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0a3af492de9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>