<?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 Oğuzhan KARACABAY on Medium]]></title>
        <description><![CDATA[Stories by Oğuzhan KARACABAY on Medium]]></description>
        <link>https://medium.com/@oguzhankrcb?source=rss-4a18c8c9504------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fXTCL6547QiFmDamRBb2jA.jpeg</url>
            <title>Stories by Oğuzhan KARACABAY on Medium</title>
            <link>https://medium.com/@oguzhankrcb?source=rss-4a18c8c9504------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 06:27:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oguzhankrcb/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[Five Ways to Run Laravel: A Runtime Comparison Journey, Part 1]]></title>
            <link>https://oguzhankrcb.medium.com/five-ways-to-run-laravel-a-runtime-comparison-journey-part-1-3f310f46a3a0?source=rss-4a18c8c9504------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f310f46a3a0</guid>
            <category><![CDATA[php-developers]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[laravel-development]]></category>
            <category><![CDATA[laravel-framework]]></category>
            <dc:creator><![CDATA[Oğuzhan KARACABAY]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 13:07:40 GMT</pubDate>
            <atom:updated>2026-08-15T13:07:40.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*43rnA9IgbfA8TSdRp1srjg.jpeg" /></figure><p>Hello, I had this idea to compare different runtimes for Laravel for a long time and finally I decided to run it.</p><p>This is going to be a journey, not just one time but I am planning to repeat this comparison as Laravel and the runtimes change.</p><h3>What I tested</h3><p>The comparison included five setups.</p><ol><li>FrankenPHP</li><li>Swoole</li><li>OpenSwoole</li><li>RoadRunner</li><li>Nginx with PHP FPM</li></ol><p>These are the exact software versions used for the final test.</p><ol><li>PHP 8.4.24</li><li>Laravel Framework 13.25.0</li><li>Laravel Octane 2.18.0</li><li>FrankenPHP 1.12.7</li><li>Swoole 6.2.2</li><li>OpenSwoole 26.2.0</li><li>RoadRunner 2025.1.15</li><li>Nginx 1.31.3</li></ol><p>All Docker base images were locked to exact digest values. Every setup used the same application source and the same Composer lock file.</p><p>Laravel Octane was used with FrankenPHP, Swoole, OpenSwoole, and RoadRunner. Each of these setups used two application workers. PHP FPM used two static children. OPcache was enabled everywhere and JIT was disabled.</p><p>Every container used PHP 8.4.24. FrankenPHP used a thread safe PHP build because that is how its official image is provided. The other setups used non thread safe builds.</p><h3>The test application</h3><p>The Laravel app had four endpoints.</p><ol><li>/api/health returned an empty 204 response.</li><li>/api/static returned a small JSON response.</li><li>/api/db ran four SQLite queries. It counted users and active products, calculated inventory value, and loaded 20 products.</li><li>/api/cpu ran 1,000 simple calculations and returned a fixed checksum.</li></ol><p>Every image used the same migrations and seed data. The database contained 100 users and 1,000 products. Exactly 900 products were active.</p><h3>The test machine and room</h3><p>I ran the test on a MacBook with an M4 Pro chip, 16 GB of memory, and 10 CPU cores. It was running macOS Version 26.5.2.</p><p>The air conditioner was set to 20°C during the test.</p><p>After the Docker images were prepared, I waited 10 minutes before the first measurement. I waited 4 minutes between endpoint measurements. After each runtime session, its containers were stopped and I waited 5 minutes before starting the next runtime.</p><p>Only one benchmark runtime was active at a time.</p><p>I run the tests 3 times for each runtime and took the average outputs.</p><h3>How to read the charts</h3><p>Each bar shows the average requests per second from three runs. A larger number means more throughput.</p><p>The thin line shows the lowest and highest result. A short line means the three results were close. A long line means performance changed more between rounds.</p><h3>Database result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UpXO6ngYpdOUVbrhGd2VeQ.png" /></figure><p>FrankenPHP had the highest database average at 611.19 requests per second. Swoole was almost identical at 610.62. Their result ranges also overlapped, so this endpoint was effectively a tie between them.</p><h3>Health result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KiUKogHX2CVE9PrC7-HbnQ.png" /></figure><p>Swoole had the highest health average at 740.50 requests per second. FrankenPHP followed at 735.77 and OpenSwoole reached 725.39. The ranges overlapped, so the difference between these three was small.</p><h3>Static JSON result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VlfhEMyaJBp3l0RMJgRMYg.png" /></figure><p>OpenSwoole had the highest static JSON average at 735.13 requests per second. Swoole followed at 731.38. FrankenPHP reached 708.08. RoadRunner reached 641.62. Nginx with PHP FPM reached 488.19.</p><h3>CPU result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1EyS1H7XtRpyHjzTGgx2Zg.png" /></figure><p>Swoole had the highest CPU average at 725.98 requests per second. OpenSwoole followed at 705.53 and FrankenPHP reached 699.57.</p><h3>Slow requests matter too</h3><p>Of course the raw results are important but there is one more important thing too and that is the P99 latency, P99 is the response time that 99 percent of requests stayed under.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wtN6VpztjNPZ2fcCU7HwEQ.png" /></figure><p>FrankenPHP had the best average P99 latency on all four endpoints.</p><ol><li>Database: 214.50 ms</li><li>Health: 178.09 ms</li><li>Static JSON: 185.58 ms</li><li>CPU: 190.18 ms</li></ol><p>This is important because FrankenPHP was also close to the throughput leaders. It did not only process many requests. Its slower requests also completed sooner in this test.</p><p>FrankenPHP gave the best balance in this small application. It was at or near the top for throughput and had the best average P99 latency everywhere.</p><h3>Limits of this test</h3><p>This test used one computer, one Laravel application, SQLite, two workers, and three rounds. A larger application may produce a different order. MySQL or PostgreSQL may also change the database result.</p><p>The test ran through Docker Desktop on macOS. It is not a direct prediction for a Linux production server.</p><h3>Repeating the test from repository</h3><p>Github Repository: <a href="https://github.com/oguzhankrcb/laravel-runtime-comparison">https://github.com/oguzhankrcb/laravel-runtime-comparison</a></p><p>The repository contains the application, Docker setup, test scripts and chart generator.</p><pre>make smoke<br>make test<br>RUN_ID=your_run_id ROUNDS=3 ENDPOINT_COOLDOWN=240 COOLDOWN=300 INITIAL_COOLDOWN=600 bash bench/run.sh all<br>make charts RUN_ID=your_run_id</pre><p>Thanks for read it so far! I hope this article gave you an idea of Laravel runtimes and their performances.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f310f46a3a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharging Laravel CI/CD Pipeline: From 9 Minutes to 2 Minutes with Pre-built MySQL Images and…]]></title>
            <link>https://oguzhankrcb.medium.com/supercharging-laravel-ci-cd-pipeline-from-9-minutes-to-2-minutes-with-pre-built-mysql-images-and-16a16e073a42?source=rss-4a18c8c9504------2</link>
            <guid isPermaLink="false">https://medium.com/p/16a16e073a42</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Oğuzhan KARACABAY]]></dc:creator>
            <pubDate>Sun, 21 Dec 2025 12:48:28 GMT</pubDate>
            <atom:updated>2025-12-21T12:48:28.296Z</atom:updated>
            <content:encoded><![CDATA[<h3>Supercharging Laravel CI/CD Pipeline: From 9 Minutes to 2 Minutes with Pre-built MySQL Images and Parallel Testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWAtvhS64yR2STEMUa-d4g.png" /></figure><p>When your test suite grows to hundreds of tests, CI/CD pipeline performance becomes critical. In this article, I’ll walk you through how I reduced our GitLab CI pipeline execution time from <strong>9+ minutes to just 2 minutes, </strong>4.5x improvement by implementing pre-built MySQL Docker images and Laravel’s parallel testing capabilities.</p><h3><strong>The Problem</strong></h3><p>Our Laravel project had <strong>555 tests with 2030 assertions</strong>, and the CI pipeline was taking around 9–9:30 minutes to complete. The main bottleneck? A 6170-line SQL schema file that was being imported on every single pipeline run.</p><pre>// Our initial migration approach<br>public function up(): void<br>{<br>    DB::unprepared(file_get_contents(database_path(&#39;migrations/database.sql&#39;)));<br>}</pre><p>This approach had several issues:</p><ul><li>SQL import was taking 180–240 seconds on each run</li><li>Tests were running sequentially</li><li>Every pipeline was doing the same repetitive work</li></ul><h3>The Solution: A Multi-Layered Approach</h3><p>To solve this problem, I needed to look at it from several different angles and come up with a solution accordingly:</p><ol><li><strong>Pre-built MySQL Docker image</strong> with databases already imported</li><li><strong>Parallel test databases</strong> (4 separate databases for concurrent test execution)</li><li><strong>Laravel Parallel Testing</strong> configuration with proper database switching</li></ol><p>Let’s dive into each component.</p><h3>Step 1: Creating the Pre-built MySQL Docker Image</h3><p>Instead of importing the SQL file on every pipeline run, I decided to bake the databases directly into a Docker image. This way, the database is ready the moment the container starts.</p><h3>The Dockerfile</h3><pre>FROM mysql:8.0.33<br><br>COPY database.sql /tmp/database.sql<br>COPY init-parallel-dbs.sh /tmp/init-parallel-dbs.sh<br>COPY docker-entrypoint-custom.sh /usr/local/bin/docker-entrypoint-custom.sh<br>RUN chmod +x /tmp/init-parallel-dbs.sh /usr/local/bin/docker-entrypoint-custom.sh<br><br>RUN mysqld --initialize-insecure --user=mysql --datadir=/var/lib/mysql<br><br>RUN mysqld --user=mysql --datadir=/var/lib/mysql --skip-networking &amp; \<br>    pid=$! &amp;&amp; \<br>    echo &quot;Waiting for MySQL to start...&quot; &amp;&amp; \<br>    sleep 10 &amp;&amp; \<br>    until mysqladmin ping --silent 2&gt;/dev/null; do \<br>        sleep 2; \<br>    done &amp;&amp; \<br>    echo &quot;MySQL started, creating databases...&quot; &amp;&amp; \<br>    /tmp/init-parallel-dbs.sh &amp;&amp; \<br>    echo &quot;Shutting down MySQL...&quot; &amp;&amp; \<br>    mysqladmin shutdown &amp;&amp; \<br>    wait $pid &amp;&amp; \<br>    rm /tmp/database.sql /tmp/init-parallel-dbs.sh<br><br>EXPOSE 3306<br><br>ENTRYPOINT [&quot;/usr/local/bin/docker-entrypoint-custom.sh&quot;]</pre><p>The key insight here is that we’re running MySQL <strong>during the Docker build process</strong>, importing our schema, and then shutting it down. The resulting image contains the fully initialized database files.</p><h3>The Database Initialization Script</h3><p>Here’s where Laravel’s parallel testing naming convention becomes important. Laravel expects test databases to follow the pattern {database}_test_{token}:</p><pre>#!/bin/bash<br>set -e<br><br>for i in $(seq 1 4); do<br>    echo &quot;Creating database: project_testing_test_$i&quot;<br>    mysql -uroot -e &quot;CREATE DATABASE IF NOT EXISTS project_testing_test_$i;&quot;<br>    mysql -uroot project_testing_test_$i &lt; /tmp/database.sql<br>done<br><br>echo &quot;All databases created successfully!&quot;</pre><blockquote><strong><em>Important:</em></strong><em> Notice the </em><em>_test_ suffix in the database names. This is crucial because Laravel&#39;s </em><em>ParallelTesting trait automatically appends </em><em>_test_{token} to your base database name.</em></blockquote><h3>The Custom Entrypoint</h3><p>Since we want to support runtime password configuration, we need a custom entrypoint:</p><pre>#!/bin/bash<br>set -e<br><br>mysqld --user=mysql --default-authentication-plugin=mysql_native_password &amp;<br>pid=$!<br><br>echo &quot;Waiting for MySQL to be ready...&quot;<br>sleep 5<br>until mysqladmin ping --silent 2&gt;/dev/null; do<br>    sleep 1<br>done<br><br>if [ -n &quot;$MYSQL_ROOT_PASSWORD&quot; ]; then<br>    echo &quot;Setting root password...&quot;<br>    mysql -uroot -e &quot;ALTER USER &#39;root&#39;@&#39;localhost&#39; IDENTIFIED BY &#39;$MYSQL_ROOT_PASSWORD&#39;;&quot;<br>    mysql -uroot -p&quot;$MYSQL_ROOT_PASSWORD&quot; -e &quot;DROP USER IF EXISTS &#39;root&#39;@&#39;%&#39;;&quot;<br>    mysql -uroot -p&quot;$MYSQL_ROOT_PASSWORD&quot; -e &quot;CREATE USER &#39;root&#39;@&#39;%&#39; IDENTIFIED BY &#39;$MYSQL_ROOT_PASSWORD&#39;;&quot;<br>    mysql -uroot -p&quot;$MYSQL_ROOT_PASSWORD&quot; -e &quot;GRANT ALL PRIVILEGES ON *.* TO &#39;root&#39;@&#39;%&#39; WITH GRANT OPTION;&quot;<br>    mysql -uroot -p&quot;$MYSQL_ROOT_PASSWORD&quot; -e &quot;FLUSH PRIVILEGES;&quot;<br>    echo &quot;Root password set successfully!&quot;<br>fi<br><br>echo &quot;MySQL is ready!&quot;<br><br>wait $pid</pre><p>Build and push the image:</p><pre>docker build -f Dockerfile.mysql-parallel -t your-registry/mysql-parallel-testing:latest .<br>docker push your-registry/mysql-parallel-testing:latest</pre><h3>Step 2: The Laravel Parallel Testing Challenge</h3><p>With our pre-built MySQL image ready, I hit an unexpected roadblock. Laravel’s ParallelTesting::setUpTestDatabase callback <strong>wasn&#39;t being triggered</strong>.</p><h3>Understanding Laravel’s ParallelTesting Internals</h3><p>Looking at Laravel’s source code in the TestDatabases trait, we can see why:</p><pre>ParallelTesting::setUpTestCase(function ($testCase) {<br>    // ... <br>    $this-&gt;whenNotUsingInMemoryDatabase(function ($database) use ($uses) {<br>        [$testDatabase, $created] = $this-&gt;ensureTestDatabaseExists($database);<br><br>        $this-&gt;switchToDatabase($testDatabase);<br><br>        if ($created) {<br>          ParallelTesting::callSetUpTestDatabaseBeforeMigratingCallbacks($testDatabase);<br>        }<br><br>        if (isset($uses[Testing\DatabaseTransactions::class])) {<br>          $this-&gt;ensureSchemaIsUpToDate();<br>        }<br><br>        if ($created) {<br>          ParallelTesting::callSetUpTestDatabaseCallbacks($testDatabase);<br>        }<br>    });<br>});</pre><p>The key line is if ($created). Since our databases already exist in the Docker image, Laravel never considers them as &quot;created,&quot; and thus never calls the setUpTestDatabase callbacks.</p><h3>The Solution: Using setUpProcess with Manual Database Switching</h3><p>I needed to:</p><ol><li>Use setUpProcess instead of setUpTestDatabase</li><li>Manually switch to the correct database based on the token</li><li>Run our seeders after the switch</li></ol><p>Here’s our TestServiceProvider:</p><pre>&lt;?php</pre><pre>namespace App\Providers;</pre><pre>use Illuminate\Support\Facades\Artisan;<br>use Illuminate\Support\Facades\DB;<br>use Illuminate\Support\Facades\ParallelTesting;<br>use Illuminate\Support\ServiceProvider;</pre><pre>class TestServiceProvider extends ServiceProvider<br>{<br>    public function register(): void {}</pre><pre>    public function boot(): void<br>    {<br>        if (app()-&gt;environment(&#39;testing&#39;)) {<br>            ParallelTesting::setUpProcess(function (int $token) {<br>                // Build the correct database name based on token<br>                $database = config(&#39;database.connections.mysql.database&#39;) . &#39;_test_&#39; . $token;<br>                <br>                // Update the configuration<br>                config([&#39;database.connections.mysql.database&#39; =&gt; $database]);<br>                <br>                // Purge and reconnect to use the new database<br>                DB::purge(&#39;mysql&#39;);<br>                DB::reconnect(&#39;mysql&#39;);<br>                <br>                // Now seed the database<br>                Artisan::call(&#39;db:seed&#39;, [&#39;--force&#39; =&gt; true]);<br>            });<br>        }<br>    }<br>}</pre><p>The critical part here is the DB::purge() and DB::reconnect() sequence. Without this, Laravel would continue using the cached connection to the original database.</p><h3>Step 3: GitLab CI Configuration</h3><p>With everything in place, our GitLab CI configuration became remarkably simple:</p><pre>variables:<br>  MYSQL_DATABASE: project_testing<br>  MYSQL_ROOT_PASSWORD: my-secret-pw</pre><pre>Unit Test:<br>  image: your-registry/php:8-4-dev<br>  stage: test<br>  variables:<br>    APP_ENV: testing<br>  services:<br>    - name: your-registry/mysql-parallel-testing-ready-db:latest<br>      alias: mysql<br>    - redis:latest<br>  script:<br>    - export DB_HOST=mysql<br>    - export REDIS_HOST=redis<br>    - composer test-coverage</pre><p>And in composer.json:</p><pre>{<br>    &quot;scripts&quot;: {<br>        &quot;test-coverage&quot;: [<br>            &quot;php artisan test --parallel --processes=4 --stop-on-failure&quot;<br>        ]<br>    }<br>}</pre><h3>Challenges I’ve Encountered</h3><h3>1. Database Naming Convention</h3><p>Initially, I’ve named our databases project_testing_1, project_testing_2, etc. But Laravel expects project_testing_test_1, project_testing_test_2. The _test_ infix is mandatory for Laravel&#39;s parallel testing to work correctly.</p><h3>2. setUpTestDatabase Never Being Called</h3><p>As explained above, since databases were pre-created, Laravel’s $created flag was always false, preventing our seeding callbacks from running. The fix was switching to setUpProcess with manual database configuration.</p><h3>Results</h3><p>Metric Before After Pipeline Duration 9–9:30 min ~2 min DB Import Time 180–240 sec 0 sec Test Execution Sequential 4 parallel processes Database Count 1 3 (1 main + 3 parallel)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*WJ_mdC548CrxwMtKvoZlGw.png" /><figcaption>Before</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*TpjYVfs2oKPUUlq6tFYcEw.png" /><figcaption>After</figcaption></figure><p><strong>That’s a 4.5x improvement in pipeline speed!</strong></p><h3>Key Takeaways</h3><ol><li><strong>Bake repetitive work into Docker images: </strong>If you’re doing the same database import on every CI run, build it into the image once.</li><li><strong>Understand Laravel’s parallel testing internals: </strong>The _test_{token} naming convention and the $created flag behavior are crucial to understand.</li><li><strong>Use </strong><strong>setUpProcess for pre-existing databases: </strong>When databases already exist, setUpTestDatabase won&#39;t be called. Use setUpProcess with manual database switching instead.</li><li><strong>Don’t forget </strong><strong>DB::purge() and </strong><strong>DB::reconnect()</strong>: When dynamically changing database configuration, you must refresh the connection.</li><li><strong>Match your parallel processes to available databases: </strong>I created 4 parallel databases and run with 4 processes. You can update it with your available CPU core count to increase parallel speed processing.</li></ol><h3>Conclusion</h3><p>Optimizing CI/CD pipelines often requires thinking outside the box. By pre-building our MySQL image with all test databases ready, we eliminated the biggest bottleneck in our pipeline. Combined with Laravel’s parallel testing, we achieved a dramatic reduction in build times.</p><p>The techniques described here can be applied to any Laravel project struggling with slow CI pipelines. The initial setup takes some effort, but the time saved on every subsequent pipeline run makes it absolutely worth it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16a16e073a42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fixing CSRF Token Mismatch Between Subdomains in Laravel (Without Sanctum)]]></title>
            <link>https://oguzhankrcb.medium.com/fixing-csrf-token-mismatch-between-subdomains-in-laravel-without-sanctum-c081463ea25b?source=rss-4a18c8c9504------2</link>
            <guid isPermaLink="false">https://medium.com/p/c081463ea25b</guid>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[csrf]]></category>
            <category><![CDATA[cookies]]></category>
            <dc:creator><![CDATA[Oğuzhan KARACABAY]]></dc:creator>
            <pubDate>Fri, 17 Oct 2025 15:14:03 GMT</pubDate>
            <atom:updated>2025-10-17T16:12:41.481Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ob288Lx-ciHTIwZtQPtaA.png" /></figure><p><em>A real-world debugging story about session isolation and CSRF failures across subdomains in Laravel.</em></p><p>CSRF errors are one of those things you think you’ve already handled until one suddenly decides to appear and ruin your evening.</p><p>I was working on a <strong>Laravel + Inertia + Vue 3</strong> application with separate environments. Everything was deployed, Redis sessions were working, HTTPS was configured, and authentication looked fine until a basic login request started failing with:</p><pre>419 Page Expired — CSRF token mismatch</pre><p>Same codebase. Same deployment. Same frontend.<br>But something subtle was off, in <strong>staging</strong>.</p><h3>The Setup</h3><pre>Production → https://example.com<br>Staging    → https://staging.example.com</pre><p>No Sanctum, no Passport. Just Laravel session-based auth with Inertia.</p><p>The frontend login looked like this:</p><pre>form.post(route(&#39;login&#39;))</pre><p>Nothing unusual. But when I logged into <strong>production</strong>, something unexpected happened on the <strong>staging</strong> domain.</p><h3>Debugging Begins</h3><p>I opened DevTools → Network tab → Cookies.<br>From https://staging.example.com, I noticed <strong>duplicate cookies</strong> were being sent, <strong>even though I wasn’t logged in there</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lsrsw3sgkNZV2TK7bdK3Yw.png" /></figure><p>This meant one thing: <strong>production cookies were being shared with the staging subdomain</strong>.<br>The browser was sending <strong>both cookies</strong>, and Axios used the wrong one leading to CSRF mismatches.</p><p>This wasn’t a frontend problem. It wasn’t Laravel being weird.<br>This was a <strong>cookie scope problem</strong>.</p><h3>Root Cause: Wrong SESSION_DOMAIN in Production</h3><p>The issue came from this incorrect <strong>production</strong> configuration:</p><pre># Problem: Cookie shared with all subdomains<br>SESSION_DOMAIN=example.com</pre><p>By specifying example.com, Laravel tells the browser:</p><blockquote><em>“Apply this cookie to example.com AND all of its subdomains.”</em></blockquote><p>That caused cookies from production to <strong>leak into</strong>:</p><pre>staging.example.com<br>api.example.com<br>anything.example.com</pre><p>Exactly what I didn’t want.</p><h3>The Fix: Host-Only Cookies in Production</h3><p>The solution was to stop explicitly setting the cookie domain in production. Instead of forcing a shared domain, I made production cookies <strong>host-only</strong>:</p><pre># Correct configuration (Production)<br>SESSION_DOMAIN=null<br>SESSION_COOKIE=prod_session</pre><p>And on staging:</p><pre># Staging (isolated)<br>SESSION_DOMAIN=null<br>SESSION_COOKIE=staging_session</pre><p>When SESSION_DOMAIN=null, Laravel does <strong>not</strong> include a Domain attribute in the cookie. Browsers interpret that as:</p><blockquote><em>“Only send this cookie to the exact host that created it.”</em></blockquote><h3>Final Thoughts</h3><p>CSRF problems in Laravel are often not framework issues, they’re usually misconfigured cookies. When dealing with multiple environments or subdomains, always double-check how your cookies are scoped. A single line like SESSION_DOMAIN=example.com can unintentionally expose sessions across environments. Keep it simple, keep it secure, and always start debugging by inspecting your cookies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c081463ea25b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Case Sensitivity Bug That Broke My Laravel Inertia Tests: A Cross-Platform Development Tale]]></title>
            <link>https://oguzhankrcb.medium.com/the-case-sensitivity-bug-that-broke-my-laravel-inertia-tests-a-cross-platform-development-tale-2dc67b4c0c5d?source=rss-4a18c8c9504------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dc67b4c0c5d</guid>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[inertia]]></category>
            <dc:creator><![CDATA[Oğuzhan KARACABAY]]></dc:creator>
            <pubDate>Sun, 01 Jun 2025 18:30:43 GMT</pubDate>
            <atom:updated>2025-06-01T18:30:43.301Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CHPjuqU1k5QxYgUx2YGcdA.png" /></figure><h3>Preliminary Information</h3><p><strong>macOS (Case-Insensitive by Default)</strong></p><ul><li>macOS uses HFS+ or APFS file systems, which are <strong>case-insensitive</strong> by default</li><li>This means Index and index are treated as the same file/directory</li><li>Your application works regardless of the case mismatch</li></ul><p><strong>Linux/Ubuntu (Case-Sensitive)</strong></p><ul><li>Linux file systems (ext4, etc.) are <strong>case-sensitive</strong></li><li>Index and index are treated as completely different files/directories</li><li>If your actual directory is named index but your config references Index, the path resolution fails</li></ul><p>When developing web applications across different operating systems, we often encounter subtle bugs that work perfectly on one platform but fail mysteriously on another. Today, I want to share a particularly frustrating case sensitivity issue I encountered with Laravel Inertia.js that cost me 2 hours of debugging and how a simple configuration change solved everything.</p><h4><strong>The Problem: Tests Passing Locally, Failing in CI</strong></h4><p><strong>Picture this scenario:</strong> You’ve written a comprehensive test suite for your Laravel application using Inertia.js. Everything works flawlessly on your local macOS development environment with PHP 8.4. Your tests pass, your application runs smoothly, and you’re confident in your code.</p><p>Then you push to your GitHub repository, and suddenly your CI pipeline starts failing with mysterious errors. The same tests that pass locally are now breaking in the Ubuntu environment of GitHub Actions.</p><p>Here’s the test that was causing all the trouble:</p><pre>#[Test]<br>public function it_can_show_appointments_index()<br>{<br>    $this-&gt;actingAs($this-&gt;doctorUser)<br>        -&gt;get(route(&#39;doctor.appointments.index&#39;))<br>        -&gt;assertStatus(200)<br>        -&gt;assertInertia(function (AssertableInertia $page) {<br>            return $page-&gt;component(&#39;Doctor/Appointments/Index&#39;)<br>                -&gt;has(&#39;appointments&#39;)<br>                -&gt;has(&#39;availableSlots&#39;);<br>        });<br>}</pre><p>This test was designed to verify that the doctor appointments index page loads correctly with the expected Inertia.js component and data. Simple enough, right?</p><p>Annnnd the error which we got in GitHub Actions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*hOpebVd73Ofm0mycP3mcQQ.png" /></figure><p>Alright, first I thought the error was about case sensitivity issue because it’s the first thing it comes to mind, then i tried to change the file name to lowercase:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*c6g_-dw2r_yCHTIKq01E2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*C8ALMv73vzBXUyJ0VJ60-w.png" /></figure><p>Still no luck! It’s the moment where i thought i must start to debugging.</p><h3>The Debugging Journey</h3><p>After encountering this issue, I went through the typical debugging checklist:</p><ol><li><strong>Environment Variables</strong>: Checked if all necessary environment variables were properly set in the CI environment</li><li><strong>Dependencies</strong>: Verified that all PHP and Node.js dependencies were correctly installed</li><li><strong>Database Setup</strong>: Ensured the test database was properly seeded</li><li><strong>File Permissions</strong>: Checked if there were any file permission issues in the CI environment</li><li><strong>PHP Version Compatibility</strong>: Confirmed PHP 8.4 compatibility across platforms</li></ol><p>Everything seemed to be in order, yet the tests continued to fail in the Ubuntu CI environment while passing perfectly on macOS.</p><p>Lastly, i created a case-sensitive macOS Volume and started to step-debug the test itself, we were failing in the line 63 of AssertableInertia.php :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*eI6cmpgWhPxdtF42ejDZcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*c_7DdklRpyyzLAQh4qMjhQ.png" /></figure><p>That wasn’t enough to learn the main problem, i went to deeper in FileViewFinder class and debugged it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T8OBP4PSea9QZ5wrnz94jw.png" /></figure><p>Did you notice the problem?</p><h3>The Eureka Moment: Pages Directory</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*Wv2s-KXBFOLO2aCp9RPUNw.png" /></figure><p>I discovered the root cause: <strong>case sensitivity in pages directory</strong>. But why was it like this? Why Inertia looks that folder with ‘Pages’ instead of ‘pages’? I had to look deeper.</p><h3>Understanding the Root Cause</h3><p>I started to debug from beginning, which in AssertableInertia.php:</p><pre>app(&#39;inertia.testing.view-finder&#39;)-&gt;find($value);</pre><p>Then i went to find method:</p><pre>public function find($name)<br>{<br>    if (isset($this-&gt;views[$name])) {<br>        return $this-&gt;views[$name];<br>    }<br><br>    if ($this-&gt;hasHintInformation($name = trim($name))) {<br>        return $this-&gt;views[$name] = $this-&gt;findNamespacedView($name);<br>    }<br><br>    return $this-&gt;views[$name] = $this-&gt;findInPaths($name, $this-&gt;paths);<br>}</pre><p>I had to find where that $this-&gt;paths coming from, so i searched and find that it was set in __construct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*YVIt7onBQ8ocRoaXsLbLSw.png" /></figure><p>Then I put a Breakpoint at line 57 and find the caller method of construct:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*aaB5THOWTVDxdTRQWzeyJQ.png" /></figure><p>Which lead me to this code block:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*wW_qcPypTJ2R2gNZV22W_w.png" /></figure><p>Annnnnddd the moment of pain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*zdNh-Sj0Ei7p6vhlLm7I7A.png" /></figure><p>All of it was in a config file and waiting us to be changed to a lowercase…</p><h3>The Solution and Best Practices</h3><h3>Immediate Fix</h3><p>Update your config/inertia.php to match the actual case of your directory structure:</p><pre>&#39;page_paths&#39; =&gt; [<br>    resource_path(&#39;js/pages&#39;),<br>],</pre><h3>Prevention Strategies</h3><ol><li><strong>Consistent Naming Convention</strong>: Establish and stick to a consistent case convention for directories (I recommend lowercase for better cross-platform compatibility)</li><li><strong>Cross-Platform Testing</strong>: If possible, test your application on both case-sensitive and case-insensitive systems before deployment</li><li><strong>CI/CD Pipeline</strong>: Always include comprehensive tests in your CI/CD pipeline running on Linux environments</li><li><strong>Directory Structure Documentation</strong>: Document your project’s directory structure and naming conventions for team members</li></ol><h3>Lessons Learned</h3><p>This experience reinforced several important principles:</p><ol><li><strong>Platform Differences Matter</strong>: Never assume that something working on one OS will work identically on another</li><li><strong>Case Sensitivity is Critical</strong>: Always be mindful of case sensitivity when working with file paths</li><li><strong>CI/CD is Essential</strong>: Continuous integration pipelines catch these platform-specific issues before production</li><li><strong>Simple Solutions</strong>: Sometimes the most frustrating bugs have the simplest solutions</li></ol><h3>Conclusion</h3><p>What started as a mysterious test failure turned into a valuable lesson about cross-platform development. A single character case difference caused hours of debugging, but ultimately led to a better understanding of how different operating systems handle file paths.</p><p>If you’re working with Laravel Inertia.js (or any framework that relies on file path resolution), always double-check that your configuration matches the actual case of your directory structure. Your future self and your CI pipeline will thank you.</p><p>Have you encountered similar cross-platform issues in your development journey? I’d love to hear about your experiences in the comments below.</p><p><em>Originally published on Medium. If you found this article helpful, please give it a clap and follow for more web development insights!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dc67b4c0c5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PHPStorm using specific PHP version for File Watcher with HERD]]></title>
            <link>https://oguzhankrcb.medium.com/phpstorm-using-specific-php-version-for-file-watcher-with-herd-24e45da0ad35?source=rss-4a18c8c9504------2</link>
            <guid isPermaLink="false">https://medium.com/p/24e45da0ad35</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[phpstorm]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Oğuzhan KARACABAY]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 15:52:40 GMT</pubDate>
            <atom:updated>2025-02-27T15:52:40.008Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SXZ3Wlex30JFGTH5" /></figure><p>Managing multiple PHP versions in a development environment can sometimes lead to unexpected challenges. Tools like <strong>HERD</strong> facilitate the use of different PHP versions seamlessly. However, global PHP version settings might cause conflicts with project-specific tools. In this article, I will share my experience of configuring <strong>PHP-CS-Fixer</strong> to operate with PHP 8.4 for a specific project, despite having PHP 8.3 set globally.</p><p><strong>The Challenge: Global PHP 8.3 Interfering with Project Requirements</strong></p><p>Initially, I utilized <strong>File Watcher</strong> in my project directory to automate <strong>PHP-CS-Fixer</strong> execution. Despite having multiple PHP versions installed via HERD, the tool defaulted to the global PHP 8.3 version, leading to compatibility issues within my project, which required PHP 8.4. Below were my initial settings:</p><p><strong>Initial File Watcher Configuration:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tWNebme9WkwdjEH-r3q8-w.png" /></figure><p>• <strong>Program:</strong> oguzhankaracabay/Desktop/projects/xxx/vendor/bin/php-cs-fixer</p><p>• <strong>Arguments:</strong> fix — using-cache=no -vvv — config=./public/bundles/.php-cs-fixer.dist.php $FilePath$</p><p>• <strong>Working Directory:</strong> $ProjectFileDir$</p><p>In this setup, PHP-CS-Fixer defaulted to the global PHP 8.3 version, causing discrepancies since my project was tailored for PHP 8.4.</p><p><strong>The Solution: Configuring File Watcher to Use PHP 8.4</strong></p><p>To resolve this, I explicitly directed File Watcher to utilize the PHP 8.4 version managed by HERD. The updated configuration was as follows.</p><p><strong>Updated File Watcher Configuration:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GuiaEIqHumLvrkvDYheC_Q.png" /></figure><p>• <strong>Program:</strong> /Users/oguzhankaracabay/Library/Application Support/Herd/bin/php84</p><p>• <strong>Arguments:</strong> /Users/oguzhankaracabay/Desktop/projects/XXX/vendor/bin/php-cs-fixer fix — using-cache=no -vvv — config=./php-cs-fixer.dist.php $FilePath$</p><p>• <strong>Working Directory:</strong> $ProjectFileDir$</p><p>• <strong>Environment Variables:</strong> PHP_CS_FIXER_IGNORE_ENV=1</p><p>By specifying the exact path to PHP 8.4 and setting the environment variable PHP_CS_FIXER_IGNORE_ENV=1, PHP-CS-Fixer operated under PHP 8.4 exclusively for this project, bypassing the global PHP 8.3 setting.</p><p><strong>Conclusion</strong></p><p>When working with multiple PHP versions using tools like HERD, it’s crucial to ensure that project-specific tools align with the required PHP version. Manually configuring tools such as File Watcher to point to the appropriate PHP executable can prevent potential conflicts arising from global PHP settings.</p><p>I hope this guide assists developers facing similar challenges in managing multiple PHP versions within their projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24e45da0ad35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Symfony Microservice architecture with gRPC communication]]></title>
            <link>https://oguzhankrcb.medium.com/introduction-to-symfony-microservice-architecture-with-grpc-communication-9ff08a23af4a?source=rss-4a18c8c9504------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ff08a23af4a</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Oğuzhan KARACABAY]]></dc:creator>
            <pubDate>Tue, 24 Dec 2024 11:23:38 GMT</pubDate>
            <atom:updated>2024-12-24T11:23:38.159Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_boYq4r2yFxMEtd_3ioyw.png" /></figure><h3>Introduction</h3><p>Hello, In this article, we will explore Symfony Microservice architecture and gRPC communication. For those unfamiliar with gRPC, we’ll start with a brief introduction. Readers already familiar with gRPC topic may skip this section.</p><p><strong>gRPC</strong>: gRPC is a high-performance, open-source remote procedure call (RPC) framework developed by Google. It enables efficient and seamless communication between applications written in different languages.</p><p>After providing this foundational knowledge, we will dive into creating a Microservice architecture with Symfony and examine how to establish communication between these services using gRPC.</p><p>First of all, PHP doesn’t have any gRPC server implementation by default. If we look at to <a href="https://grpc.io/docs/languages/php/basics/">official documentation</a> of gRPC we can see that only a client for gRPC can be created in PHP language.</p><p>So we must first solve the server issue and this is exactly where Roadrunner comes to our rescue.</p><h3>Roadrunner</h3><p>Roadrunner is a high-performance application server, load balancer, and PHP process manager written in Go. By operating as an HTTP or gRPC server, it forwards requests to a pool of constantly running PHP processes via the Goridge binary protocol. This design keeps PHP workers alive, eliminating the need to restart them with each request — unlike the traditional Nginx + PHP-FPM setup.</p><h3>Requirements</h3><ul><li><a href="https://getcomposer.org/">Composer</a></li><li><a href="https://www.docker.com/get-started/">Get Started | Docker</a></li></ul><ul><li>Composer for creating symfony projects</li><li>Docker for EVERYTHING else we need :)</li></ul><h3>.proto File</h3><p>A <strong>.proto file</strong> is a way to define how data is structured and how services are called when using <a href="https://developers.google.com/protocol-buffers">Protocol Buffers (Protobuf)</a>. Essentially, it describes:</p><p>1. <strong>What data we want to send</strong> (the messages).</p><p>2. <strong>What operations we can perform</strong> (the services and their methods).</p><p>First of all, we must create a .proto file which will define our contract between Client and Product services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L2AD1ew9Tr8mQnUIOtRrKQ.png" /><figcaption>Definition of service.proto file with diagram</figcaption></figure><h4>service.proto:</h4><pre>syntax = &quot;proto3&quot;;<br><br>package grpc.ProductService;<br><br>service ClientProductService {<br>  rpc GetProductsByClient(ClientRequest) returns (ProductResponse);<br>}<br><br>message ClientRequest {<br>  string client_id = 1;<br>}<br><br>message Product {<br>  string client_id = 1;<br>  string product_id = 2;<br>  string name = 3;<br>  string description = 4;<br>  double price = 5;<br>}<br><br>message ProductResponse {<br>  repeated Product products = 1;<br>}</pre><p>Below is a step-by-step explanation of each element in our .proto file:</p><p>1. <strong>Syntax</strong> = “proto3”;</p><p>• Indicates we’re using Protocol Buffers version 3 (the modern version).</p><p>2. P<strong>ackage</strong> grpc.ProductService;</p><p>• Groups everything into a namespace called grpc.ProductService.</p><p>3. <strong>Service: </strong>ClientProductService</p><p>• Defines one remote procedure call, GetProductsByClient, which takes a ClientRequest and returns a ProductResponse.</p><p>4. <strong>Message: </strong>ClientRequest</p><p>• Has a single field, client_id, which specifies the client whose products we want.</p><p>5. <strong>Message: </strong>Product</p><p>• Represents an individual product with fields for client_id, product_id, name, description, and price.</p><p>6. <strong>Message: </strong>ProductResponse</p><p>• Contains a repeated Product products field — a list of Product items to return for the request.</p><h4>In short:</h4><p>• ClientRequest says, “Here is the client_id. I need the products belonging to this client.”</p><p>• GetProductsByClient says, “Given a ClientRequest, I’ll return a ProductResponse containing all the products for that client.”</p><p>• ProductResponse says, “Here’s a <strong>list</strong> of Product objects, each with client_id, product_id, name, description, and price.”</p><h3>Creating Symfony projects</h3><p>First create a main directory which will contain our services.</p><pre>mkdir symfony-microservices-example<br>cd symfony-microservices-example</pre><p>Then create our services.</p><pre>composer create-project symfony/skeleton ProductService<br>composer create-project symfony/skeleton ClientService</pre><p>At this point we will have 2 projects named ProductService and ClientService</p><p>In this project we are going to use Docker for our needs. So create a directory for our base Dockerfile.</p><pre>cd symfony-microservices-example<br>mkdir BaseDocker<br>cd BaseDocker<br>touch Dockerfile</pre><p><strong>Base Dockerfile:</strong></p><pre>FROM php:8.3-cli-alpine<br><br>WORKDIR /app<br><br>COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/bin/<br><br>RUN install-php-extensions bcmath intl opcache zip sockets grpc protobuf<br><br>COPY --from=composer:2 /usr/bin/composer /usr/bin/composer<br><br>RUN apk add --no-cache --virtual .build-deps \<br>        $PHPIZE_DEPS \<br>        linux-headers \<br>    &amp;&amp; mkdir -p /tmp/pear/cache \<br>    &amp;&amp; apk add --update --no-cache \<br>        openssl-dev \<br>        cmake \<br>        libunwind \<br>        libunwind-dev \<br>        pcre-dev \<br>        icu-dev \<br>        icu-data-full \<br>        libzip-dev \<br>        git \<br>        go \<br>    &amp;&amp; mkdir /build &amp;&amp; cd /build \<br>    &amp;&amp; git clone --recursive -b v1.27.x https://github.com/grpc/grpc \<br>    &amp;&amp; mkdir -p /build/grpc/cmake/build &amp;&amp; cd /build/grpc/cmake/build \<br>    &amp;&amp; cmake ../.. \<br>    &amp;&amp; make protoc grpc_php_plugin \<br>    &amp;&amp; cd /build \<br>    &amp;&amp; composer create-project --ignore-platform-reqs spiral/roadrunner-cli \<br>    &amp;&amp; chmod +x ./roadrunner-cli/bin/rr \<br>    &amp;&amp; ./roadrunner-cli/bin/rr download-protoc-binary -l /usr/bin \<br>    &amp;&amp; cp /build/grpc/cmake/build/grpc_php_plugin /usr/bin \<br>    &amp;&amp; cp /build/grpc/cmake/build/third_party/protobuf/protoc /usr/bin \<br>    &amp;&amp; chmod +x /usr/bin/protoc-gen-php-grpc \<br>    &amp;&amp; chmod +x /usr/bin/grpc_php_plugin \<br>    &amp;&amp; chmod +x /usr/bin/protoc \<br>    &amp;&amp; rm -rf /build \<br>    &amp;&amp; pecl clear-cache \<br>    &amp;&amp; apk del --purge .build-deps</pre><p>Let’s build this image with the below command (it can take up to 10 minutes to build):</p><pre>docker build -t base-php8.3-with-grpc:latest .</pre><p>If you don’t have time to build your own image you can use my pre-build image from: <a href="https://hub.docker.com/r/oguzhankrcb/base-php8.3-with-grpc">https://hub.docker.com/r/oguzhankrcb/base-php8.3-with-grpc</a></p><p>And then we will create our docker-compose.yaml :</p><pre>services:<br>  service_a:<br>    build:<br>      context: ./ProductService<br>    ports:<br>      - &quot;8084:8084&quot;<br>    volumes:<br>      - ./ProductService:/app/<br>    networks:<br>      - app-network<br>  service_b:<br>    build:<br>      context: ./ClientService<br>    ports:<br>      - &quot;8085:8085&quot;<br>    volumes:<br>      - ./ClientService:/app/<br>    networks:<br>      - app-network<br><br>networks:<br>  app-network:<br>    driver: bridge</pre><p>We will need specific Dockerfiles for our both ProductService and ClientService projects.</p><p><strong>ClientService Dockerfile:</strong></p><pre>FROM base-php8.3-with-grpc:latest<br><br>WORKDIR /app<br>COPY . .<br><br>CMD [&quot;php&quot;, &quot;-S&quot;, &quot;0.0.0.0:8085&quot;, &quot;-t&quot;, &quot;public/&quot;]</pre><p><strong>ProductService Dockerfile:</strong></p><pre>FROM base-php8.3-with-grpc:latest<br><br>WORKDIR /app<br>COPY . .<br><br>CMD [&quot;php&quot;, &quot;-S&quot;, &quot;0.0.0.0:8084&quot;, &quot;-t&quot;, &quot;public/&quot;]</pre><p>Finally we can build our compose file:</p><pre>docker compose build --no-cache</pre><h4>Installing roadrunner-bundle</h4><p>The <a href="https://github.com/Baldinof/roadrunner-bundle"><strong><em>baldinof/roadrunner-bundle</em></strong></a> package streamlines integration with RoadRunner in Symfony by providing a pre-configured worker, various settings, and configuration options. It simplifies the process of getting started with Symfony and RoadRunner together. To install the package, run the following command and confirm the recipe installation (y):</p><pre>docker compose run service_a composer require baldinof/roadrunner-bundle</pre><p>Once installed, the bundle will be automatically registered, and the necessary configuration files will be generated.</p><p>We will update the RoadRunner configuration files, .rr.yaml and .rr.dev.yaml, as follows:</p><p>1. <strong>Remove the unnecessary http plugin:</strong></p><p>The http section, which is no longer required, will be removed. Here’s an example of the section to delete:</p><pre>http:<br>  address: 0.0.0.0:8080<br>  ...</pre><p>2. <strong>Add the grpc section:</strong></p><p>We’ll replace the removed http section with a configuration for the gRPC plugin. The updated configuration will look like this:</p><pre>grpc:<br>  listen: &quot;tcp://0.0.0.0:8084&quot;<br>  proto:<br>    - &quot;proto/service.proto&quot;</pre><p>Don’t forge to move our previously written service.proto file to ./ProductService/proto/service.proto .</p><p>Then let’s run this command to install grpc/grpc and spiral/roadrunner-grpc packages:</p><pre>docker compose run service_a composer require grpc/grpc spiral/roadrunner-grpc</pre><p>Then we must download roadrunner binary in order to run roadrunner server:</p><pre>docker compose run service_a composer require --dev spiral/roadrunner-cli<br>docker compose run service_a ./vendor/bin/rr get-binary -l ./bin<br>cd ProductService/bin<br>chmod u+x rr</pre><h3>Generating gRPC codes</h3><p>To generate PHP code for the gRPC server and client, we will use protoc, the utility responsible for code generation. This requires a plugin for PHP gRPC code generation, specifically protoc-gen-php-grpc.</p><p>• <strong>Server Code Generation:</strong></p><p>For the server, we’ll use the protoc-gen-php-grpc plugin provided by the RoadRunner project. However, this plugin does not generate client classes.</p><p>• <strong>Client Code Generation:</strong></p><p>To generate client classes, we’ll use the official grpc_php_plugin. Unfortunately, this plugin must be manually built from source, which can involve resolving dependencies and may be time-consuming.</p><p>To simplify the process, I’ve prepared a Docker image that builds protoc, grpc_php_plugin, and protoc-gen-php-grpc for you. Using this image eliminates the need for manual setup. It handles the entire process automatically.</p><p><strong>Steps to Generate the Code:</strong></p><p>1. <strong>Create a Directory for the Generated Code:</strong></p><p>We’ll store the generated code in a directory named generated. Create the directory with:</p><pre>mkdir ./generated</pre><p>2. <strong>Run the Code Generation Command:</strong></p><p>Both server and client code can be generated using the same command, differing only in the — plugin argument.</p><p>With this setup, you’ll have a seamless process for generating both server and client code in the generated directory.</p><h4>Server Code (ProductService)</h4><p>We will generate our server stubs with the protoc-gen-php-grpc plugin:</p><pre>docker compose run service_a protoc \<br>  --plugin=protoc-gen-grpc=/usr/bin/protoc-gen-php-grpc \<br>  --php_out=./generated \<br>  --grpc_out=./generated \<br>  ./proto/service.proto</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*EgbFeD9EGFYreeKWjXOn_w.png" /></figure><p>We must see the above files in our project.</p><h4>Implementing ProductService Class</h4><p>We are going to develop our gRPC request handler class, let’s create ProductService/src/Services/ProductService.php file:</p><pre>&lt;?php<br><br>namespace App\Services;<br><br>use Faker\Factory;<br>use Faker\Generator;<br>use Grpc\ProductService\ClientProductServiceInterface;<br>use Grpc\ProductService\ClientRequest;<br>use Grpc\ProductService\Product;<br>use Grpc\ProductService\ProductResponse;<br><br>use Spiral\RoadRunner\GRPC;<br><br>class ProductService implements ClientProductServiceInterface<br>{<br>    protected Generator $faker;<br>    public function __construct()<br>    {<br>        $this-&gt;faker = Factory::create();<br>    }<br><br>    public function GetProductsByClient(GRPC\ContextInterface $ctx, ClientRequest $in): ProductResponse<br>    {<br>        $productResponse = new ProductResponse();<br><br>        $productResponse-&gt;setProducts($this-&gt;getRandomProducts($in-&gt;getClientId()));<br><br>        return $productResponse;<br>    }<br><br>    private function getRandomProducts(string $clientId): array<br>    {<br>        $products = [];<br><br>        $randomLength = random_int(3, 5);<br>        for ($i = 0; $i &lt; $randomLength; $i++) {<br>            $product = (new Product())-&gt;setProductId($i + 1)<br>                -&gt;setClientId($clientId)<br>                -&gt;setName($this-&gt;faker-&gt;domainName)<br>                -&gt;setDescription($this-&gt;faker-&gt;word)<br>                -&gt;setPrice($this-&gt;faker-&gt;numberBetween(100,1000));<br><br>            $products[] = $product;<br>        }<br><br>        return $products;<br>    }<br>}</pre><p>Don’t forget to add faker package:</p><pre>docker compose run service_a composer require fzaninotto/faker --dev</pre><p>Now we are going to refactor our Dockerfile to start our gRPC server with roadrunner:</p><pre>FROM base-php8.3-with-grpc:latest<br><br>WORKDIR /app<br>COPY . .<br><br>CMD [&quot;/app/bin/rr&quot;, &quot;serve&quot;, &quot;-d&quot;, &quot;-c&quot;, &quot;/app/.rr.yaml&quot;]</pre><p>Then to autoload generated files, we must add the following lines to the composer.json:</p><pre>...<br>&quot;autoload&quot;: {<br>  &quot;psr-4&quot;: {<br>    ...<br>    &quot;GPBMetadata\\&quot;: &quot;generated/GPBMetadata&quot;,<br>    &quot;Grpc\\&quot;: &quot;generated/Grpc&quot;<br>  }<br>},<br>...</pre><p>After that we must run composer dump-autoload:</p><pre>docker compose run service_a composer du</pre><p>Then let’s build and run our compose file:</p><pre>docker compose build --no-cache<br>docker compose up</pre><p>If you did everything right then you must see a screen like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*to4R6WvtogfWMbW4Vy1afg.png" /></figure><p>Now we can test our server with grpcurl tool or something like that, i will use grpcurl if you use macOS you can download it with brew :</p><pre>brew install grpcurl</pre><p>And run the below command to test:</p><pre>grpcurl -plaintext -d &#39;{&quot;client_id&quot;:&quot;123456&quot;}&#39; -import-path ./proto -proto service.proto localhost:8084 grpc.ProductService.ClientProductService/GetProductsByClient</pre><p>You must saw a response like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*trmwlcSWe7WMVoieGhkKzQ.png" /></figure><h4>Client Code (ClientService)</h4><p>First of all we must install grpc/grpc package to use grpc client :</p><pre>docker compose run service_b composer req grpc/grpc</pre><p>Then copy our service.proto file to ClientService/proto/service.proto and create generated directory as ClientService/generated and run the command:</p><pre>docker compose run service_b protoc \                                                                                                          ✔ │ 3m 51s  │ system  │ 17:01:13  <br>  --plugin=protoc-gen-grpc=/usr/bin/grpc_php_plugin \<br>  --php_out=./generated \<br>  --grpc_out=./generated \<br>  ./proto/service.proto</pre><p>And the below files must be created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*x-rqMc8y9SSUhFTW-J7WgA.png" /></figure><p>Then you must enable ext-grpc extension from your composer.json:</p><pre>...<br>  &quot;require&quot;: {<br>    ...<br>    &quot;ext-grpc&quot;: &quot;*&quot;,<br>    ...<br>  },<br>...</pre><h4>Implementing ClientProductController</h4><p>Now we are going to develop our ClientProductController , so create a file to src/Controller/ClientProductController.php :</p><pre>&lt;?php<br><br>declare(strict_types=1);<br><br>namespace App\Controller;<br><br>use Grpc\ChannelCredentials;<br>use Grpc\ProductService\ClientProductServiceClient;<br>use Grpc\ProductService\ClientRequest;<br>use Grpc\ProductService\ProductResponse;<br>use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;<br>use Symfony\Component\HttpFoundation\JsonResponse;<br>use Symfony\Component\HttpFoundation\Response;<br>use Symfony\Component\Routing\Attribute\Route;<br><br>class ClientProductController extends AbstractController<br>{<br>    #[Route(&#39;/clients/{client_id}/products&#39;, name: &#39;app_client_products&#39;, methods: [&#39;GET&#39;])]<br>    public function clientProducts(string $client_id): Response<br>    {<br>        $productClient = new ClientProductServiceClient(&#39;service_a:8084&#39;, [<br>            &#39;credentials&#39; =&gt; ChannelCredentials::createInsecure(),<br>        ]);<br><br>        $productRequest = (new ClientRequest())-&gt;setClientId($client_id);<br><br>        /** @var ProductResponse $response */<br>        [$response] = $productClient-&gt;GetProductsByClient($productRequest)-&gt;wait();<br><br>        return JsonResponse::fromJsonString($response-&gt;serializeToJsonString());<br>    }<br>}</pre><p>Then don’t forget to add our namespaces to composer.json:</p><pre>...<br>&quot;autoload&quot;: {<br>  &quot;psr-4&quot;: {<br>    ...<br>    &quot;GPBMetadata\\&quot;: &quot;generated/GPBMetadata&quot;,<br>    &quot;Grpc\\&quot;: &quot;generated/Grpc&quot;<br>  }<br>},<br>...</pre><p>Run below command to dump-autoload:</p><pre>docker compose run service_b composer du</pre><p>Finally we can up our compose file:</p><pre>docker compose up</pre><p>If we did everything right we can go to that URL:</p><pre>http://localhost:8085/clients/1234/products</pre><p>And when we open this URL we will see a response like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*yVDJkLZE1Tdu5Ht9P-57Yg.png" /></figure><h3>Conclusion</h3><p>In this article, we explored the process of setting up a Symfony-based microservice architecture using gRPC communication and learned that how combining Symfony’s flexibility with gRPC’s efficiency can create a robust foundation for scalable, high-performance microservices.</p><p>Whether you’re building an enterprise application or experimenting with modern architectures, this approach offers a practical roadmap for PHP developers to harness the potential of gRPC communication. With this knowledge, you’re equipped to design and implement your own gRPC-powered microservice solutions in Symfony.</p><p><strong>You can find the ready-to-go source code of this project from my github</strong></p><blockquote><a href="https://github.com/oguzhankrcb/symfony-micro-service-with-grpc"><strong>https://github.com/oguzhankrcb/symfony-micro-service-with-grpc</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ff08a23af4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom DQL usage with Symfony]]></title>
            <link>https://medium.com/beyn-technology/custom-dql-usage-with-symfony-a62965154172?source=rss-4a18c8c9504------2</link>
            <guid isPermaLink="false">https://medium.com/p/a62965154172</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[doctrine]]></category>
            <category><![CDATA[dql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[symfony]]></category>
            <dc:creator><![CDATA[Oğuzhan KARACABAY]]></dc:creator>
            <pubDate>Tue, 05 Sep 2023 12:35:37 GMT</pubDate>
            <atom:updated>2023-09-05T12:35:37.684Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*DZRONSa8pICwOyNA62ZaXg.png" /></figure><p>Hello, in this article I will talk about the usage and benefits of Custom DQL in Symfony.</p><p>First of all, for those who are unfamiliar, I will explain Doctrine and then DQL. Those who are already familiar with this topic can skip this section.</p><p><strong>Doctrine</strong>: It is an ORM (Object Relational Mapping) tool used for PHP applications. It provides us the ability to work in an object-oriented manner, abstracts basic SQL queries, and offers a more intuitive way to interact with database data.</p><p><strong>DQL (Doctrine Query Language)</strong>: It is a specialized query language that forms the foundation of Doctrine ORM. Although it has a structure similar to SQL, its most important feature is the ability to easily write relationships between objects.</p><p>An example of a DQL string:</p><blockquote>SELECT c FROM Customer c JOIN c.orders o WHERE o.totalAmount &gt; 100</blockquote><p>As you can see above, we filtered by joining the Orders relation through the Customer Entity, and we did this in a simple and understandable language.</p><p>Now that we assume everyone has a basic understanding, let’s gradually move on to what Custom DQL is, what it’s used for, and how to write it.</p><p>Custom DQL commands are customized DQL commands. There might be functions that DQL doesn’t provide, and we may want to develop them ourselves. Let’s write a DQL that takes a given string, splits it, and returns the desired index as an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c5445cacb13deefe1a368466a108c6c/href">https://medium.com/media/0c5445cacb13deefe1a368466a108c6c/href</a></iframe><p>In Custom DQLs, there are two functions we need to pay attention to: getSql and parse. In the parse section, we need to specify the components of the function we are creating. The Lexer assists us in this; it recognizes different components (such as keywords, field names, operators, etc.) within the DQL query. It then breaks down these components into pieces for later interpretation and processing. Let&#39;s go through the process step by step.</p><p>First, let’s prepare an example DQL command:</p><blockquote>“SELECT SPLIT_STR(‘a|bb|ccc|dd’, ‘|’, 3) FROM Product e”</blockquote><p>Next, let’s see how this DQL command is processed in the parse() function:</p><blockquote>$parser-&gt;match(Lexer::T_IDENTIFIER);</blockquote><p>In the first step, we try to match our SPLIT_STR function; our functions are also referred to as an IDENTIFIER. When this process is successfully completed, it automatically moves on to the next token.</p><blockquote>$parser-&gt;match(Lexer::T_OPEN_PARENTHESIS);</blockquote><p>In the second step, we look for the opening parenthesis in our function, i.e., the opening parenthesis in SPLIT_STR(.</p><blockquote>$this-&gt;stringExpression = $parser-&gt;StringPrimary();</blockquote><p>In the third step, after the opening parenthesis, we parse the string we want to split, which is our first parameter.</p><blockquote>$parser-&gt;match(Lexer::T_COMMA);</blockquote><p>Then we match the , to look for the second parameter.</p><blockquote>$this-&gt;delimiterExpression = $parser-&gt;StringPrimary();</blockquote><p>We parse the delimiter we will use for splitting (|).</p><blockquote>$parser-&gt;match(Lexer::T_COMMA);</blockquote><p>We match the , again to look for the third parameter.</p><blockquote>$this-&gt;positionExpression = $parser-&gt;ArithmeticPrimary();</blockquote><p>We successfully parse the third parameter.</p><blockquote>$parser-&gt;match(Lexer::T_CLOSE_PARENTHESIS);</blockquote><p>Finally, we match the closing parenthesis ) to finish the parsing process.</p><p>After our parser is processed, we move on to the getSQL function. This function should return a string SQL statement:</p><pre>public function getSql(SqlWalker $sqlWalker)<br>    {<br>        return sprintf(<br>            &#39;REPLACE(SUBSTRING(SUBSTRING_INDEX(%s, %s, %s), &#39; .<br>            &#39;LENGTH(SUBSTRING_INDEX(%s, %s, %s - 1)) + 1), %s, \&#39;\&#39;)&#39;,<br>            $this-&gt;stringExpression-&gt;dispatch($sqlWalker),<br>            $this-&gt;delimiterExpression-&gt;dispatch($sqlWalker),<br>            $this-&gt;positionExpression-&gt;dispatch($sqlWalker),<br>            $this-&gt;stringExpression-&gt;dispatch($sqlWalker),<br>            $this-&gt;delimiterExpression-&gt;dispatch($sqlWalker),<br>            $this-&gt;positionExpression-&gt;dispatch($sqlWalker),<br>            $this-&gt;delimiterExpression-&gt;dispatch($sqlWalker)<br>        );<br>    }</pre><p>With sprintf, we prepare the necessary arrangements and place our parsed DQL data&#39;s expressions into the SQL code. This turns the following code:</p><blockquote>SELECT SPLIT_STR(‘a|bb|ccc|dd’, ‘|’, 3) FROM Product e</blockquote><p>Through DQL processing, it becomes:</p><blockquote>SELECT REPLACE(SUBSTRING(SUBSTRING_INDEX(‘a|bb|ccc|dd’, ‘|’, 3), LENGTH(SUBSTRING_INDEX(‘a|bb|ccc|dd’, ‘|’, 3–1)) + 1), ‘|’, ‘’) AS sclr_0 FROM Products p0_</blockquote><p>Finally, in order for DQL to recognize the SPLIT_STR function, we need to open our doctrine.yaml file and make the following adjustments:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b99723c12163435aa075dd70a9730310/href">https://medium.com/media/b99723c12163435aa075dd70a9730310/href</a></iframe><p>I would like to provide an example related to real-life usage alongside what we have done so far.</p><p>Normally, you cannot execute the GROUP_CONCAT SQL function in DQL because DQL doesn’t recognize the GROUP_CONCAT function, and you would get an error like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DpC4CKes5iOPkF2iBvcdUQ.png" /></figure><p>We were able to solve this situation very easily using Custom DQL:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d58335fae58f6430df345d91c0c0f6b2/href">https://medium.com/media/d58335fae58f6430df345d91c0c0f6b2/href</a></iframe><p>Of course, the specific solution above was evaluated based on our usage of GROUP_CONCAT in the project. This serves as an example of using this Custom DQL:</p><pre>&#39;GROUP_CONCAT((SELECT c.id FROM App\Entity\xx c WHERE pp.value = c.id AND pp.name = \&#39;xxx\&#39;)) as x&#39;,<br>&#39;GROUP_CONCAT((SELECT c2.id FROM App\Entity\yy c2 WHERE pp.value = c2.id AND pp.name = \&#39;yyy\&#39;)) as y&#39;,</pre><p>In summary, writing Custom DQL allows us to create SQL functions that are either not supported by DQL or would normally be complex and lengthy. This makes life easier for us by simplifying the process :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a62965154172" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beyn-technology/custom-dql-usage-with-symfony-a62965154172">Custom DQL usage with Symfony</a> was originally published in <a href="https://medium.com/beyn-technology">Beyn Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading QR codes with Laravel and increasing the QR reading rate with image processing]]></title>
            <link>https://oguzhankrcb.medium.com/reading-qr-codes-with-laravel-and-increasing-the-qr-reading-rate-with-image-processing-273970f3bd41?source=rss-4a18c8c9504------2</link>
            <guid isPermaLink="false">https://medium.com/p/273970f3bd41</guid>
            <category><![CDATA[qr-code]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[invoice-processing]]></category>
            <category><![CDATA[image-processing]]></category>
            <dc:creator><![CDATA[Oğuzhan KARACABAY]]></dc:creator>
            <pubDate>Tue, 29 Nov 2022 18:53:43 GMT</pubDate>
            <atom:updated>2022-11-29T18:58:37.076Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*0IwO0VtN3Oi6Laj5m410YA.png" /></figure><p>Hello, in this article, I will talk about how we can cut a QR code from a document, how we can read the QR code in this cut section and how we can increase the reading rate with Laravel.</p><h4>Creating Laravel project</h4><p>If you have composer installed on your computer, you can create a Laravel project as follows. If Composer is not installed, you need to install it.</p><pre>composer create-project laravel/laravel qr-project</pre><p>We can install the packages we need to use with Composer as follows:</p><pre>composer require simplesoftwareio/simple-qrcode &quot;~4&quot;<br>composer require tarfin-labs/zbar-php<br>composer require laraveldaily/laravel-invoices:^3.0</pre><p>Don’t forget to install the laravel-invoices package:</p><pre>php artisan invoices:install<br>php artisan invoices:update</pre><p>You must also install the zbar and imagemagick tools in order to run some of the packages. Thanks to the zbar tool, we will be able to read QR code, and thanks to the imagemagick we will be able to perform image processing. You can access the installation pages from the links below:</p><ul><li><a href="https://zbar.sourceforge.net/download.html">ZBar bar code reader</a></li><li><a href="https://imagemagick.org/script/download.php">Download</a></li></ul><p>macOS and Homebrew users can easily install both Tools using the following bash commands:</p><pre>brew install pkg-config imagemagick<br>brew install zbar</pre><p>After installing Imagemagick, it should not be forgotten to install the relevant PHP Extension, we also install the extension using PECL:</p><pre>/opt/homebrew/opt/php@8.1/bin/pecl install imagick</pre><p>Since I’m using Homebrew, my php/bin location is as above, yours may be different, so you need to change the location yourself.</p><p>After the installation process is finished, let’s open our project with the help of any IDE. Let’s create a folder called Services under the app directory in order to be able to create and view invoices, and inside this folder, let’s create two more folders called InvoiceService and Facades. After the process is finished, our directory structure should be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a084RM3t6rMB8oOob0yMKA.png" /></figure><p>Next, let’s create an empty class named InvoiceService under our InvoiceService folder, then create another class called InvoiceServiceProvider and change its content as follows:</p><pre>&lt;?php<br><br>namespace App\Services\InvoiceService;<br><br>use Illuminate\Support\ServiceProvider;<br><br>class InvoiceServiceProvider extends ServiceProvider<br>{<br>    public function register(): void<br>    {<br>        $this-&gt;app-&gt;singleton(InvoiceService::class, function ($app) {<br>            return new InvoiceService();<br>        });<br>    }<br>}</pre><p>Thus, we have created a singleton for our InvoiceService class, thanks to this singleton pattern, we will be able to access and use all functions in our class as if they are static functions. All that remains is to create a Facade, let’s create a PHP class named InvoiceService in our Services/Facades folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apLDECWmOnGfq-CssQFoTg.png" /></figure><p>Now we can introduce our ServiceProvider to Laravel and access our InvoiceService class as a singleton from anywhere in the project.</p><p>To introduce the ServiceProvider to Laravel, let’s open config/app.php and add it as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_B9cL1VE1uvc-9UY4mHZaw.png" /></figure><p>Finally, we introduce our Facade to the project and conclude:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5T2HrjyWtrCjyloxCvlJA.png" /></figure><h4>Creating InvoiceService</h4><p>Now that we can start writing our InvoiceService class, let’s first write an ordinary invoice document creation function:</p><pre>&lt;?php<br><br>namespace App\Services\InvoiceService;<br><br>use Illuminate\Http\Response;<br>use LaravelDaily\Invoices\Classes\Buyer;<br>use LaravelDaily\Invoices\Classes\InvoiceItem;<br>use LaravelDaily\Invoices\Invoice;<br><br>class InvoiceService<br>{<br>    /**<br>     * @throws \Illuminate\Contracts\Container\BindingResolutionException<br>     * @throws \Exception<br>     */<br>    public function createInvoiceAsPdf(): string<br>    {<br>        $customer = new Buyer([<br>            &#39;name&#39;          =&gt; &#39;John Doe&#39;,<br>            &#39;custom_fields&#39; =&gt; [<br>                &#39;email&#39; =&gt; &#39;test@example.com&#39;,<br>            ],<br>        ]);<br><br>        $item = (new InvoiceItem())-&gt;title(&#39;Service 1&#39;)-&gt;pricePerUnit(2);<br><br>        $invoice = Invoice::make()<br>            -&gt;buyer($customer)<br>            -&gt;discountByPercent(10)<br>            -&gt;taxRate(15)<br>            -&gt;shipping(2)<br>            -&gt;addItem($item);<br><br>        return $invoice-&gt;render()-&gt;output;<br>    }<br>}</pre><p>After this process, we can access our function as InvoiceService::createInvoiceAsPdf()</p><h4>Creating InvoiceController</h4><p>Let’s run the following artisan command in terminal:</p><pre>php artisan make:controller InvoiceController --invokable</pre><p>Then, let’s code the InvoiceController class as follows:</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use App\Services\Facades\InvoiceService;<br>use Illuminate\Http\Response;<br>use Illuminate\Support\Facades\Storage;<br><br>class InvoiceController extends Controller<br>{<br>    public function __invoke()<br>    {<br>        return response()<br>            -&gt;streamDownload(<br>                callback: function (): void {<br>                    echo InvoiceService::createInvoiceAsPdf();<br>                },<br>                name: &#39;invoice.pdf&#39;<br>            );<br>    }<br>}</pre><h4>Creating Route</h4><p>Let’s open the routes/web.php file and change it as follows:</p><pre>&lt;?php<br><br>use App\Http\Controllers\InvoiceController;<br>use Illuminate\Support\Facades\Route;<br><br>Route::get(&#39;/get-invoice&#39;, InvoiceController::class);</pre><p>Now, when we enter the get-invoice URL in our project, we expect the file to be downloaded as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qm0e3aPmKL0TDPhofxU54w.png" /></figure><h4>Adding QR code to invoice</h4><p>We have successfully created our invoice, next to add a QR code to our invoice, first we open our InvoiceService class and add a custom order_id and qr_data variable to our invoice template:</p><pre>&lt;?php<br><br>namespace App\Services\InvoiceService;<br><br>use Illuminate\Http\Response;<br>use LaravelDaily\Invoices\Classes\Buyer;<br>use LaravelDaily\Invoices\Classes\InvoiceItem;<br>use LaravelDaily\Invoices\Invoice;<br>use SimpleSoftwareIO\QrCode\Facades\QrCode;<br><br>class InvoiceService<br>{<br>    /**<br>     * @throws \Illuminate\Contracts\Container\BindingResolutionException<br>     * @throws \Exception<br>     */<br>    public function createInvoiceAsPdf(): string<br>    {<br>        $customer = new Buyer([<br>            &#39;name&#39;          =&gt; &#39;John Doe&#39;,<br>            &#39;custom_fields&#39; =&gt; [<br>                &#39;email&#39; =&gt; &#39;test@example.com&#39;,<br>            ],<br>        ]);<br><br>        $item = (new InvoiceItem())-&gt;title(&#39;Service 1&#39;)-&gt;pricePerUnit(2);<br><br>        $invoice = Invoice::make()<br>            -&gt;buyer($customer)<br>            -&gt;discountByPercent(10)<br>            -&gt;taxRate(15)<br>            -&gt;shipping(2)<br>            -&gt;addItem($item);<br><br>        $invoice-&gt;setCustomData([<br>           &#39;order_id&#39; =&gt; $orderId = random_int(100000,999999),<br>           &#39;qr_data&#39;  =&gt; base64_encode(QrCode::format(&#39;png&#39;)-&gt;size(100)-&gt;generate($orderId)),<br>        ]);<br><br>        return $invoice-&gt;render()-&gt;output;<br>    }<br>}</pre><p>Then we open our blade file located in resources/views/vendor/invoices/templates/default.blade.php and add something as follows:</p><pre>        {{-- Header --}}<br>        @if($invoice-&gt;logo)<br>            &lt;img src=&quot;{{ $invoice-&gt;getLogo() }}&quot; alt=&quot;logo&quot; height=&quot;100&quot;&gt;<br>        @endif<br><br>        &lt;p class=&quot;text-right m-5&quot;&gt;<br>            &lt;img<br>                src=&quot;data:image/png;base64,<br>                {!! $invoice-&gt;getCustomData()[&#39;qr_data&#39;] !!} &quot;<br>            &gt;<br>        &lt;/p&gt;</pre><p>And we add this class to the Style part:</p><pre>       .m-5 {<br>                margin-right: 3rem !important;<br>                margin-top: 3rem !important;<br>            }</pre><p>When we save the changes in our blade file and create the invoice again, we should have seen an image like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QPWW3EZtnjFO58dXocixIA.png" /></figure><h4>Reading QR code from invoice</h4><p>First of all, let’s copy the invoice we created with the file path as storage/app/public/invoice.pdf</p><p>Now, we will cut this QR code from the invoice file we have created and scan it. If we try to read the QR code without cutting it, the probability of capturing the QR code in the whole file decreases considerably, so we have to perform the cutting process. Let’s create a structure like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d3WICu0Il7uthRbB5ysC8g.png" /></figure><p>Let’s not forget to add our ServiceProvider and Facade alias in config/app.php</p><p>Let’s open our ImageProcessingService class and edit it as follows:</p><pre>&lt;?php<br><br>namespace App\Services\ImageProcessingService;<br><br>use Illuminate\Support\Facades\Storage;<br>use Illuminate\Support\Str;<br>use Imagick;<br>use TarfinLabs\ZbarPhp\Exceptions\ZbarError;<br>use TarfinLabs\ZbarPhp\Zbar;<br><br>class ImageProcessingService<br>{<br>    public int $edgeLength = 240;<br><br>    /**<br>     * @throws \ImagickException<br>     * @throws \TarfinLabs\ZbarPhp\Exceptions\UnableToOpen<br>     * @throws \TarfinLabs\ZbarPhp\Exceptions\InvalidFormat<br>     * @throws \Exception<br>     */<br>    public function readQrCode(string $filePath): string|null<br>    {<br>        $cropedQRPath = &#39;public/&#39;.Str::random(40).&#39;.png&#39;;<br>        $imagickInstance = $this-&gt;cropQrCodeFromPDF($filePath);<br><br>        Storage::put($cropedQRPath, $imagickInstance-&gt;getImageBlob());<br><br>        try {<br>            $readedCode = (new Zbar(Storage::path($cropedQRPath)))-&gt;scan();<br>        } catch (ZbarError) {<br>            $readedCode = null;<br>        }<br><br>        Storage::delete($cropedQRPath);<br><br>        return $readedCode;<br>    }<br><br>    /**<br>     * @throws \Exception<br>     */<br>    public function cropQrCodeFromPDF(string $filePath): Imagick<br>    {<br>        $imagick = new Imagick();<br>        $imagick-&gt;setResolution(128, 128);<br>        $imagick-&gt;readImageBlob(Storage::get($filePath));<br><br>        $imageWidth = $imagick-&gt;getImageWidth() - $this-&gt;edgeLength;<br>        $imagick-&gt;cropImage($this-&gt;edgeLength + 80, $this-&gt;edgeLength + 80, $imageWidth - 80 , 0);<br>        $imagick-&gt;resizeImage($this-&gt;edgeLength + 80, $this-&gt;edgeLength + 80, 1, 0);<br><br>        $imagick-&gt;setImageFormat(&#39;png&#39;);<br><br>        return $imagick;<br>    }<br><br><br>}</pre><p>After editing our class, let’s create a Controller named ImageProcessingController :</p><pre>php artisan make:controller ImageProcessingController --invokable</pre><p>And let’s edit its content as follows:</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use App\Services\Facades\ImageProcessingService;<br>use Illuminate\Http\JsonResponse;<br><br>class ImageProcessingController extends Controller<br>{<br>    /**<br>     * Handle the incoming request.<br>     */<br>    public function __invoke(): JsonResponse<br>    {<br>        return \response()-&gt;json([<br>           &#39;code&#39; =&gt; ImageProcessingService::readQrCode(&#39;public/invoice.pdf&#39;)<br>        ]);<br>    }<br>}</pre><p>Then let’s open routes/web.php and edit it as follows:</p><pre>&lt;?php<br><br>use App\Http\Controllers\ImageProcessingController;<br>use App\Http\Controllers\InvoiceController;<br>use Illuminate\Support\Facades\Route;<br><br>Route::get(&#39;/get-invoice&#39;, InvoiceController::class);<br>Route::get(&#39;/process-qr-code&#39;, ImageProcessingController::class);</pre><p>Let’s open our browser and enter the URL /process-qr-code and see the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e3oLcasZLVABh59ilmNXQg.png" /></figure><p>As you can see, the QR code we produced was successfully read and the result was sent to us in Response.</p><h4>Increasing QR reading rate with image processing</h4><p>QR codes may not be very readable in documents scanned in daily life, so there are a few image processing techniques that can be done to increase the reading rate, i won’t go into too much detail about the operations done because if we include the image processing part in the article, it’s sure this will be a very long article :) but if i need to explain in a small way, the operations performed help us to obtain a more distinctive QR code by whitening the pixels that do not belong to the QR code in the background and making the QR code part black.</p><p>Let’s open our ImageProcessingService class and edit the readerQrCode function as follows:</p><pre>/**<br>     * @throws \ImagickException<br>     * @throws \TarfinLabs\ZbarPhp\Exceptions\UnableToOpen<br>     * @throws \TarfinLabs\ZbarPhp\Exceptions\InvalidFormat<br>     * @throws \Exception<br>     */<br>    public function readQrCode(string $filePath): string|null<br>    {<br>        $cropedQRPath = &#39;public/&#39;.Str::random(40).&#39;.png&#39;;<br>        $imagickInstance = $this-&gt;cropQrCodeFromPDF($filePath);<br><br>        Storage::put($cropedQRPath, $imagickInstance-&gt;getImageBlob());<br><br>        try {<br>            $readedCode = (new Zbar(Storage::path($cropedQRPath)))-&gt;scan();<br>        } catch (ZbarError) {<br>            $imagickInstance-&gt;setImageBackgroundColor(&#39;#FFFFFF&#39;);<br>            $imagickInstance-&gt;mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);<br>            $imagickInstance-&gt;setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);<br>            $imagickInstance-&gt;autoLevelImage();<br><br>            $imagickInstance-&gt;autoThresholdImage(1); // 1 means we choose OTSU threshold method<br><br>            $kernel = ImagickKernel::fromBuiltIn(Imagick::KERNEL_SQUARE, &#39;1&#39;);<br>            $imagickInstance-&gt;morphology(\Imagick::MORPHOLOGY_OPEN, 1, $kernel);<br><br>            Storage::disk(&#39;local&#39;)-&gt;put($cropedQRPath, $imagickInstance-&gt;getImageBlob());<br><br>            try {<br>                $readedCode = (new Zbar(Storage::path($cropedQRPath)))-&gt;scan();<br>            } catch (ZbarError) {<br>                $readedCode = null;<br>            }<br>        }<br><br>        Storage::delete($cropedQRPath);<br><br>        return $readedCode;<br>    }</pre><p>The reason why we do these operations after the catch (ZbarError) part is that if the QR code reading is successful, we do not need to take any extra action, and if we failed to read the QR code, the image processing algorithms will save us time.</p><p>You can read this article in both <a href="https://medium.com/@oguzhankrcb/laravel-ile-qr-kod-okuma-ve-g%C3%B6rsel-i%C5%9Fleme-kullanarak-okuma-oran%C4%B1n%C4%B1-artt%C4%B1rma-810a61ddf006">Turkish</a> and <a href="https://medium.com/@oguzhankrcb/reading-qr-codes-with-laravel-and-increasing-the-qr-reading-rate-with-image-processing-273970f3bd41">English</a> languages.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=273970f3bd41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel automatic object casting to known data types in JsonResources]]></title>
            <link>https://oguzhankrcb.medium.com/laravel-automatic-object-casting-to-known-data-types-in-jsonresources-29df4f3506c9?source=rss-4a18c8c9504------2</link>
            <guid isPermaLink="false">https://medium.com/p/29df4f3506c9</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel-framework]]></category>
            <dc:creator><![CDATA[Oğuzhan KARACABAY]]></dc:creator>
            <pubDate>Wed, 14 Sep 2022 14:43:48 GMT</pubDate>
            <atom:updated>2022-09-14T14:45:49.790Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/882/0*rveKnlQLo4Pt_zzf.png" /><figcaption>Photography: <a href="http://stevenrombauts.be/about"><em>Steven Rombauts</em></a></figcaption></figure><p>First of all, I want to start with explaining the problem; Let’s say we have an Order model for managing orders with two attributes: price and product_name. The price attribute is <a href="https://laravel.com/docs/9.x/eloquent-mutators#array-and-json-casting">casted</a> to a Money object.</p><p>The Order eloquent model would be look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/862b08445cd6a0469e7ff0df73942ab1/href">https://medium.com/media/862b08445cd6a0469e7ff0df73942ab1/href</a></iframe><p>The OrderController will be probably like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/638597f0c9b39d2649a14e137eb16c07/href">https://medium.com/media/638597f0c9b39d2649a14e137eb16c07/href</a></iframe><p>And the OrderResource probably like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72b1d8f585d9dd0e318f89d56d1a1d8c/href">https://medium.com/media/72b1d8f585d9dd0e318f89d56d1a1d8c/href</a></iframe><p>If we want to fetch an Order record through the OrderController above, we’ll get a JSON like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ddcdb1c18e35dc76071268573c1d3b1/href">https://medium.com/media/1ddcdb1c18e35dc76071268573c1d3b1/href</a></iframe><p>See? The price attribute of the order model is empty ’cause it is casted to a Money object. To solve this issue; You should convert the Money object into an integer or float on every resource that uses this type of money object.</p><p><strong>Our Solution</strong></p><p>Just import the `AutoCastingJsonResource` trait into your Laravel Resource and override the `casts` method like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/faa87afd98dfa8132a754ece64504069/href">https://medium.com/media/faa87afd98dfa8132a754ece64504069/href</a></iframe><p>The package will scan all attributes on the resource and run the specified closure for the given attribute instance type. So we get results like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e404a1b2f60470a059d78b563ae405f/href">https://medium.com/media/0e404a1b2f60470a059d78b563ae405f/href</a></iframe><p>As you can see, the Money object is casted to the integer automatically.</p><p><strong>Solution For All Resources</strong></p><p>But if you pay your attention, you can see that actually we didn’t solve the problem about fixing casting problem for all resources right? It just solves the problem for one Resource, not for all. Okey then, now we can implement a BaseJsonResource which will fix that problem for us:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99a36e1827abf3e4fc824752609a30d4/href">https://medium.com/media/99a36e1827abf3e4fc824752609a30d4/href</a></iframe><p>Now, we can extend our all resources from this BaseJsonResource like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c644b91c1ccdf015c998a6489929c7d9/href">https://medium.com/media/c644b91c1ccdf015c998a6489929c7d9/href</a></iframe><p>After we done with extending BaseJsonResource everything should work fine:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e404a1b2f60470a059d78b563ae405f/href">https://medium.com/media/0e404a1b2f60470a059d78b563ae405f/href</a></iframe><p>This article co-written by <a href="https://medium.com/@oguzhan.karacabay">Oğuzhan Karacabay</a>, <a href="https://medium.com/@deligoez">Yunus Emre Deligöz</a> and available in both <a href="https://medium.com/@oguzhankrcb/laravel-automatic-object-casting-to-known-data-types-in-jsonresources-29df4f3506c9">English</a> and <a href="https://medium.com/@oguzhankrcb/laravelde-jsonresource-i%C3%A7erisinde-ki-objelerin-bilindik-t%C3%BCrden-veri-tiplerine-otomatik-%C3%A7evirilmesi-ea7d09aa87e0">Turkish</a>.</p><p>A github link to AutoCastingJsonResource package : <a href="https://github.com/oguzhankrcb/auto-casting-json-resource">https://github.com/oguzhankrcb/auto-casting-json-resource</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29df4f3506c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>