<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Bertug Korucu</title>
    <description>The latest articles on Forem by Bertug Korucu (@bertugkorucu).</description>
    <link>https://forem.com/bertugkorucu</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F245053%2Fbf207efe-ea74-4328-bc5e-68e2ae136ec0.jpeg</url>
      <title>Forem: Bertug Korucu</title>
      <link>https://forem.com/bertugkorucu</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/bertugkorucu"/>
    <language>en</language>
    <item>
      <title>Executing Shell Commands In Laravel</title>
      <dc:creator>Bertug Korucu</dc:creator>
      <pubDate>Wed, 17 Nov 2021 21:45:20 +0000</pubDate>
      <link>https://forem.com/kodeas/executing-shell-commands-in-laravel-1098</link>
      <guid>https://forem.com/kodeas/executing-shell-commands-in-laravel-1098</guid>
      <description>&lt;p&gt;Both &lt;code&gt;shell_exec()&lt;/code&gt; and &lt;code&gt;exec()&lt;/code&gt; do the job - until they don't. &lt;/p&gt;

&lt;p&gt;If your command crash for some reason, you won't know -  &lt;strong&gt;&lt;code&gt;shell_exec()&lt;/code&gt; and &lt;code&gt;exec()&lt;/code&gt; don't throw Exceptions.&lt;/strong&gt; They just fail silently. 😱&lt;/p&gt;

&lt;p&gt;So, here is my solution to encounter this problem:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use Symfony\Component\Process\Process;

class ShellCommand
{
    public static function execute($cmd): string
    {
        $process = Process::fromShellCommandline($cmd);

        $processOutput = '';

        $captureOutput = function ($type, $line) use (&amp;amp;$processOutput) {
            $processOutput .= $line;
        };

        $process-&amp;gt;setTimeout(null)
            -&amp;gt;run($captureOutput);

        if ($process-&amp;gt;getExitCode()) {
            $exception = new ShellCommandFailedException($cmd . " - " . $processOutput);
            report($exception);

            throw $exception;
        }

        return $processOutput;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;It utilises Symfony's Process (which comes out of the box to Laravel).&lt;/em&gt; ✨&lt;/p&gt;

&lt;p&gt;With this way, I can throw a custom exception, log the command and the output to investigate, report it to my logs to investigate, etc.&lt;/p&gt;

&lt;p&gt;No more failing silently 😇&lt;/p&gt;

&lt;p&gt;Hope you like this little piece! If you do, please give it a ❤️&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>php</category>
    </item>
    <item>
      <title>Bulk Update Multiple Records with Separate Data — Laravel</title>
      <dc:creator>Bertug Korucu</dc:creator>
      <pubDate>Sun, 11 Jul 2021 23:45:04 +0000</pubDate>
      <link>https://forem.com/kodeas/bulk-update-multiple-records-with-separate-data-laravel-4j7k</link>
      <guid>https://forem.com/kodeas/bulk-update-multiple-records-with-separate-data-laravel-4j7k</guid>
      <description>&lt;p&gt;As a rule of thumb, we should never run database queries inside a for-loop!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;“Database transaction” is an expensive operation.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For example, let’s say we designed an inventory software and it’s being used in production for a year, and reached 1,000,000 transactions.&lt;/p&gt;

&lt;p&gt;Suddenly, we learnt that we didn’t add the VAT to our transactions. For the transactions in the future, it’s pretty easy to deal with, maybe with a mutator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Transaction extends Model { 
    public $vat = 0.20;

    public function setPriceAttribute($value) {
        $this-&amp;gt;attributes['price'] += $value * $this-&amp;gt;vat;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Future records are pretty easy to deal with. However how are we going to edit the 1 million records from the past.&lt;/p&gt;

&lt;p&gt;For editing data from the past, I prefer to create a Seeder.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;php artisan make:seeder AddVatToTransactions&lt;/code&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  How not to do it?
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz4zndxs8ysb5s7fbw5r4.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz4zndxs8ysb5s7fbw5r4.jpeg" alt="Drake says no" width="451" height="451"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class AddVatToTransactions extends Seeder {

  public function run() 
  {
    $vat = 0.20;
    $transactions = Transaction::get();

    foreach ($transactions as $transaction) {
       $transaction-&amp;gt;price += $transaction-&amp;gt;price * $vat
       $transaction-&amp;gt;save();
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, running it in a loop of 1 million and making a “database transaction” in each iteration of the loop — not a good idea! (Spoiler Alert: It’ll freeze your system 😀)&lt;/p&gt;




&lt;h4&gt;
  
  
  Then, how to do it?
&lt;/h4&gt;

&lt;p&gt;Again, in our &lt;code&gt;AddVatToTransactions&lt;/code&gt; Seeder:&lt;/p&gt;

&lt;p&gt;The idea in mysql query is “CASE Statements”&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;UPDATE db.transactions
SET PRICE = CASE  
              WHEN id = 3 THEN 500
              WHEN id = 4 THEN 300
           END 
WHERE ID IN (3, 4)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Now, let’s do it in Laravel:
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$vat = 0.20;
$transactions = Transaction::get();

$cases = [];
$ids = [];
$params = [];

foreach ($transactions as $transaction) {
    $cases[] = "WHEN {$transaction-&amp;gt;id} then ?";
    $params[] = $transaction-&amp;gt;profit * $vat;
    $ids[] = $transaction-&amp;gt;id;
}

$ids = implode(',', $ids);
$cases = implode(' ', $cases);

if (!empty($ids)) {
    \DB::update("UPDATE transactions SET `price` = CASE `id` {$cases} END WHERE `id` in ({$ids})", $params);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will make one database transaction to write it all your updates.⚡️&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiq7j5qnkh4ejehqx0lme.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiq7j5qnkh4ejehqx0lme.jpeg" alt="Drake says yes" width="263" height="192"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;🗣 I can hear some of you saying: “It’s still FREEZING”&lt;/p&gt;

&lt;h3&gt;
  
  
  So.. Optimizing it even further:
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;#1: “Select” only the data you need from the database to consume less RAM.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In our example, we only use “id” and “price” columns. So let’s only select them.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$transactions = Transaction::select('id', 'price')-&amp;gt;get();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;#2: “Chunk” your collection to separate your transaction to multiple database transactions.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Laravel, you can chunk collections like&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Transaction::get()-&amp;gt;chunk(5000);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h3&gt;
  
  
  Let’s apply all in our example
&lt;/h3&gt;

&lt;p&gt;Here, first we divide our &lt;code&gt;$transactions&lt;/code&gt; collection into 5000 chunks and we do a “database transaction” per 5k records at once.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$vat = 0.20;
$transactions = Transaction::get();

foreach ($transactions-&amp;gt;chunk(5000) as $chunk) {
   $cases = [];
   $ids = [];
   $params = [];

   foreach ($chunk as $transaction) {
       $cases[] = "WHEN {$transaction-&amp;gt;id} then ?";
       $params[] = $transaction-&amp;gt;profit * $vat;
       $ids[] = $transaction-&amp;gt;id;
   }

   $ids = implode(',', $ids);
   $cases = implode(' ', $cases);

   if (!empty($ids)) {
       \DB::update("UPDATE transactions SET `price` = CASE `id` {$cases} END WHERE `id` in ({$ids})", $params);
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Hope you like this trick!&lt;/p&gt;

&lt;p&gt;Please let me know what you think in the comments 💬&lt;/p&gt;

&lt;p&gt;Happy coding! 😊&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>mysql</category>
    </item>
    <item>
      <title>Using Vite with Inertia — Laravel, Vue &amp; Tailwind</title>
      <dc:creator>Bertug Korucu</dc:creator>
      <pubDate>Sun, 11 Jul 2021 23:24:57 +0000</pubDate>
      <link>https://forem.com/kodeas/using-vite-with-inertia-laravel-vue-tailwind-2h5k</link>
      <guid>https://forem.com/kodeas/using-vite-with-inertia-laravel-vue-tailwind-2h5k</guid>
      <description>&lt;p&gt;&lt;strong&gt;TLDR; 5800ms (Laravel Mix) to 224ms (Vite⚡️) on hot-reload!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We’ve been using Laravel-Mix for years and it’s been doing pretty good. However, recently we decided to build a project using Inertia.js (which was an awesome decision).&lt;/p&gt;

&lt;p&gt;As the project started to grow, the development became a pain to wait for the webpack compiling.&lt;/p&gt;

&lt;p&gt;Then, we decided to give &lt;a href="https://vitejs.dev"&gt;Vite&lt;/a&gt; (from Vue’s creator Evan You) and the results were… ASTONISHING! I’ve been seeing Vite around in Twitter, but to be honest with you, I was not expecting THIS MUCH OF SPEED! 🚀&lt;/p&gt;

&lt;h3&gt;
  
  
  Laravel-Mix was getting too so slow. 🐢
&lt;/h3&gt;

&lt;p&gt;Benchmark Test on Hot Reloading &lt;em&gt;(with 16" MBP 64gb ram, 2.4 GHz 8-Core Intel Core i9)&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;|    Compilation     | Laravel Mix | Vite  |
|--------------------|-------------|-------|
| Initial Compile    | 13257ms     | 636ms |
| Change Reflection  | 5848ms      | 224ms |
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That’s like ‘20x for initial compilation’ and ‘25x when code change’ 😲&lt;/p&gt;

&lt;p&gt;We are fascinated by results, so let me tell you how to set it up, so you can try it out too.&lt;/p&gt;

&lt;h3&gt;
  
  
  Migrating To Vite⚡️
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;First, you’ll need to install Vite:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install vite
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Then, install Tailwind
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i tailwindcss postcss autoprefixer -D
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create “vite.config.js” and “postcss.config.js” in your project base
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { resolve } = require('path');
import vue from '@vitejs/plugin-vue';

export default ({ command }) =&amp;gt; ({
  base: command === 'serve' ? '' : '/dist/',
  publicDir: 'fake_dir_so_nothing_gets_copied',
  build: {
    manifest: true,
    outDir: resolve(__dirname, 'public/dist'),
    rollupOptions: {
      input: 'resources/js/app.js',
    },
  },

  plugins: [vue()],

  resolve: {
    alias: {
      '@': resolve('./resources/js'),
    },
  },
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }, 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;For the sake of completeness, here is Tailwind config (JIT is amazing as well!)&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;module.exports = {
  mode: "jit",
  purge: ['./resources/**/*.{js,jsx,ts,tsx,vue,blade.php}'],
  theme: {},
  variants: {},
  plugins: [],
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;And finally, you need to configure your app.js for Vite to work with Inertia.js. (The production compiling part kept me in the dark for a few hours)
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'vite/dynamic-import-polyfill';
import '../css/app.css';
import { createApp, h } from 'vue'
import { App, plugin } from '@inertiajs/inertia-vue3'

let asyncViews = () =&amp;gt; {
  return import.meta.glob('./Pages/**/*.vue');
}

const app = createApp({
  render: () =&amp;gt; h(App, {
    initialPage: JSON.parse(el.dataset.page),
        resolveComponent: async name =&amp;gt; {
            if (import.meta.env.DEV) {
                return (await import(`./Pages/${name}.vue`)).default;
            } else {
                let pages = asyncViews();
                const importPage = pages[`./Pages/${name}.vue`];
                return importPage().then(module =&amp;gt; module.default);
            }
        }
    })
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Few things to keep in mind are:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;You can’t use &lt;code&gt;require("file")&lt;/code&gt; syntax, so you always need to use &lt;code&gt;import * from file.js&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;You need to specify file extensions when importing Vue components, like &lt;code&gt;import FormInput from "@/Shared/Form/FormInput.vue"&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;"app.js" is the only point of entry for your app, so you need to import your app.css file in your app.js.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;…and your front-end is ready 🎉&lt;/strong&gt;&lt;/p&gt;




&lt;h3&gt;
  
  
  Setting up Laravel and package.json scripts
&lt;/h3&gt;

&lt;p&gt;I wanted to run “hot reloading” as well as “production” environment interchangeably in my local, so I came up with the below solution. (If you figure out a better way, I’d be happy to hear)&lt;/p&gt;

&lt;p&gt;Vite in 'dev mode' creates a local server in &lt;a href="https://localhost:3000"&gt;https://localhost:3000&lt;/a&gt; (which can be configured in vite.config.js) whereas in ‘production mode’, it creates files in 'public/dist'.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Edit your ‘package.json’ file accordingly:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"scripts": {
    "predev": "printf \"dev\" &amp;gt; public/hot",
    "dev": "vite",
    "preprod": "printf \"prod\" &amp;gt; public/hot",
    "prod": "vite build"
},
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;npm run vite&lt;/code&gt; is hot reloading itself and npm run dev is just for alias. The “pre” hooks are used to create a file in public directory so that the backend can figure out which mode is running.&lt;/p&gt;

&lt;p&gt;Finally, you need to create a helper to resolve the path in your blade &lt;br&gt;
— just like Laravel Mix’s &lt;code&gt;{{ mix('/js/app.js') }}&lt;/code&gt; helper.&lt;/p&gt;

&lt;p&gt;You can create this php file in 'app/Helpers/vite.php' (or anywhere you like)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

use Illuminate\Support\HtmlString;

if (! function_exists('vite_assets')) {
    /**
     * @return HtmlString
     * @throws Exception
     */
    function vite_assets(): HtmlString
    {
        $devServerIsRunning = false;

        if (app()-&amp;gt;environment('local')) {
            try {
                $devServerIsRunning = file_get_contents(public_path('hot')) == 'dev';
            } catch (Exception) {}
        }

        if ($devServerIsRunning) {
            return new HtmlString(&amp;lt;&amp;lt;&amp;lt;HTML
            &amp;lt;script type="module" src="http://localhost:3000/@vite/client"&amp;gt;&amp;lt;/script&amp;gt;
            &amp;lt;script type="module" src="http://localhost:3000/resources/js/app.js"&amp;gt;&amp;lt;/script&amp;gt;
        HTML);
        }
        $manifest = json_decode(file_get_contents(
            public_path('dist/manifest.json')
        ), true);
        return new HtmlString(&amp;lt;&amp;lt;&amp;lt;HTML
        &amp;lt;script type="module" src="/dist/{$manifest['resources/js/app.js']['file']}"&amp;gt;&amp;lt;/script&amp;gt;
        &amp;lt;link rel="stylesheet" href="/dist/{$manifest['resources/js/app.js']['css'][0]}"&amp;gt;
    HTML);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;And include it to your &lt;code&gt;composer.json&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"autoload": {
    "psr-4": {...},
    "files": [
        "app/Helpers/vite.php"
    ]
},
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;[make sure to run:&lt;code&gt;composer dump-autoload&lt;/code&gt;]&lt;/p&gt;

&lt;p&gt;And finally add it to your master.blade.php&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;!-- Stuff --&amp;gt;
    {{ vite_assets() }}
    &amp;lt;!-- More Stuff --&amp;gt;
&amp;lt;/head&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h4&gt;
  
  
  🏁 You are all set. Enjoy the super-speed compiling times ⚡️
&lt;/h4&gt;




&lt;p&gt;I believe this will change your development experience as drastic as it did to me! 🚀&lt;/p&gt;

&lt;p&gt;I’m really curious about your compiling speeds, please leave a comment. 💬&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>vue</category>
      <category>tailwindcss</category>
      <category>inertiajs</category>
    </item>
  </channel>
</rss>
