<?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 Tanvir Hossen Bappy on Medium]]></title>
        <description><![CDATA[Stories by Tanvir Hossen Bappy on Medium]]></description>
        <link>https://medium.com/@tanvirhossenbappy751?source=rss-d8f8c06b0a32------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1ChUHDjzQmv8QFhzElA-Ig.png</url>
            <title>Stories by Tanvir Hossen Bappy on Medium</title>
            <link>https://medium.com/@tanvirhossenbappy751?source=rss-d8f8c06b0a32------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 14:00:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tanvirhossenbappy751/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[# Demystifying Concurrency and Parallelism in Golang]]></title>
            <link>https://medium.com/@tanvirhossenbappy751/demystifying-concurrency-and-parallelism-in-golang-5a4a6c195951?source=rss-d8f8c06b0a32------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a4a6c195951</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[parallelism]]></category>
            <category><![CDATA[golang-development]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Tanvir Hossen Bappy]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 17:38:15 GMT</pubDate>
            <atom:updated>2026-04-10T17:45:33.815Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_FTURXe4o40n6GpHA3_gTQ.png" /></figure><ul><li>The two most confused concepts in Go — finally made simple.*</li></ul><p>If you’ve been writing Go for a while, you’ve probably heard:</p><h3>&gt; *”Go is great for concurrency!”*</h3><p>And maybe you nodded along… while secretly wondering: *isn’t that just parallelism?*</p><p>Nope. They’re different. And Go makes this distinction clearer than almost any other language.</p><p>Let’s break it down — no PhD required.</p><p>— -</p><h3><strong>🧠 The Mental Model First</strong></h3><p>Before any code, let’s use a real-life analogy.</p><p>**Concurrency** is a *chef* in a kitchen managing multiple dishes at once — they stir the soup, then chop vegetables, then check the oven. They’re juggling tasks, but only doing *one thing at a time*.</p><p>**Parallelism** is *multiple chefs*, each cooking a different dish *simultaneously* — at the exact same moment.</p><p>&gt; **Concurrency** = dealing with many things at once.<br>&gt; **Parallelism** = doing many things at once.</p><p>Rob Pike (one of Go’s creators) put it perfectly:<br>&gt; *”Concurrency is about structure. Parallelism is about execution.”*</p><p>— -</p><h3>🐹 How Go Thinks About This</h3><p>Go was built with concurrency as a first-class citizen. The tools it gives you are:</p><p>- **Goroutines** — lightweight threads managed by Go’s runtime<br>- **Channels** — the way goroutines talk to each other<br>- **`sync` package** — for coordination when channels aren’t the right tool</p><p>These tools let you *structure* your program concurrently. Whether it runs in *parallel* depends on your hardware (number of CPU cores) and the `GOMAXPROCS` setting.</p><p>— -</p><h3>👶 Concurrency in Go — Your First Goroutine</h3><pre>package main<br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br>func brewCoffee() {<br> fmt.Println(&quot;☕ Brewing coffee…&quot;)<br> time.Sleep(2 * time.Second)<br> fmt.Println(&quot;☕ Coffee is ready!&quot;)<br>}<br>func makeToast() {<br> fmt.Println(&quot;🍞 Making toast…&quot;)<br> time.Sleep(1 * time.Second)<br> fmt.Println(&quot;🍞 Toast is ready!&quot;)<br>}<br>func main() {<br> go brewCoffee() // run concurrently<br> go makeToast() // run concurrently<br>time.Sleep(3 * time.Second) // wait for both to finish<br> fmt.Println(&quot;🥣 Breakfast is served!&quot;)<br>}</pre><p>**Output:**<br>```<br>🍞 Making toast…<br>☕ Brewing coffee…<br>🍞 Toast is ready!<br>☕ Coffee is ready!<br>🥣 Breakfast is served!<br>```</p><p>Notice — you didn’t wait for coffee to finish before starting toast. That’s **concurrency**. The two tasks are interleaved in time.</p><p>— -</p><h3>🚨 The Problem With `time.Sleep`</h3><p>Using `time.Sleep` to wait for goroutines is a code smell. What if coffee takes longer than expected? Your program exits early.</p><p>The right tool: **`sync.WaitGroup`**</p><pre>package main<br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br> &quot;time&quot;<br>)<br>func brewCoffee(wg *sync.WaitGroup) {<br> defer wg.Done() // signal: &quot;I&#39;m done&quot;<br> fmt.Println(&quot;☕ Brewing coffee…&quot;)<br> time.Sleep(2 * time.Second)<br> fmt.Println(&quot;☕ Coffee is ready!&quot;)<br>}<br>func makeToast(wg *sync.WaitGroup) {<br> defer wg.Done()<br> fmt.Println(&quot;🍞 Making toast…&quot;)<br> time.Sleep(1 * time.Second)<br> fmt.Println(&quot;🍞 Toast is ready!&quot;)<br>}<br>func main() {<br> var wg sync.WaitGroup<br>wg.Add(2) // we&#39;re launching 2 goroutines<br> go brewCoffee(&amp;wg)<br> go makeToast(&amp;wg)<br>wg.Wait() // block until both call Done()<br> fmt.Println(&quot;🥣 Breakfast is served!&quot;)<br>}</pre><p>Clean, predictable, no magic sleep timers. ✅</p><p>— -</p><h3>📡 Goroutines Talking: Channels</h3><p>Goroutines don’t share memory by default — they *communicate* through channels.</p><p>Think of a channel like a **conveyor belt** between two workers.</p><pre>package main<br>import &quot;fmt&quot;<br>func calculateSum(nums []int, ch chan int) {<br> sum := 0<br> for _, n := range nums {<br> sum += n<br> }<br> ch &lt;- sum // send result through channel<br>}<br>func main() {<br> numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}<br>ch := make(chan int)<br>// Split the work between two goroutines<br> go calculateSum(numbers[:5], ch) // first half<br> go calculateSum(numbers[5:], ch) // second half<br>result1 := &lt;-ch // receive from channel<br> result2 := &lt;-ch // receive from channel<br>fmt.Println(&quot;Total:&quot;, result1+result2) // Total: 55<br>}</pre><p>Two goroutines each handle half the work, then send their results back. The main function collects both. This is **concurrent** work — and if you have two CPU cores available, Go may run these truly **in parallel**.</p><p>— -</p><h3>⚡ So When Does It Become Parallel?</h3><p>Go’s scheduler decides this. By default, Go uses all available CPU cores (`GOMAXPROCS` = number of cores).</p><p>You can check or set it manually:</p><pre>package main<br>import (<br> &quot;fmt&quot;<br> &quot;runtime&quot;<br>)<br>func main() {<br> fmt.Println(&quot;CPUs available:&quot;, runtime.NumCPU())<br> fmt.Println(&quot;Goroutines running in parallel:&quot;, runtime.GOMAXPROCS(0))<br>}</pre><p>- **1 CPU core** → your goroutines are concurrent but *not* parallel (the scheduler switches between them)<br>- **4 CPU cores** → goroutines *can* run in parallel, 4 at a time</p><p>&gt; The code you write is the same. Go’s runtime handles the rest.</p><p>— -</p><h3>🏎️ A Real Parallel Example — CPU-Bound Work</h3><p>Let’s say you need to process 1 million records. Without parallelism:</p><pre>package main<br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br>func processRecord(id int) int {<br> // Simulate CPU work<br> return id * id<br>}<br>func main() {<br> start := time.Now()<br> <br> total := 0<br> for i := 0; i &lt; 1_000_000; i++ {<br> total += processRecord(i)<br> }<br> <br> fmt.Printf(&quot;Done in %v\n&quot;, time.Since(start))<br>}</pre><p>Now with goroutines + channels for parallel processing:</p><pre>package main<br>import (<br> &quot;fmt&quot;<br> &quot;runtime&quot;<br> &quot;sync&quot;<br> &quot;time&quot;<br>)<br>func processChunk(start, end int, ch chan int, wg *sync.WaitGroup) {<br> defer wg.Done()<br> sum := 0<br> for i := start; i &lt; end; i++ {<br> sum += i * i<br> }<br> ch &lt;- sum<br>}<br>func main() {<br> numCPU := runtime.NumCPU()<br> total := 1_000_000<br> chunkSize := total / numCPU<br>ch := make(chan int, numCPU)<br> var wg sync.WaitGroup<br>startTime := time.Now()<br>for i := 0; i &lt; numCPU; i++ {<br> wg.Add(1)<br> start := i * chunkSize<br> end := start + chunkSize<br> go processChunk(start, end, ch, &amp;wg)<br> }<br>go func() {<br> wg.Wait()<br> close(ch)<br> }()<br>result := 0<br> for partial := range ch {<br> result += partial<br> }<br>fmt.Printf(&quot;Done in %v\n&quot;, time.Since(startTime))<br>}</pre><p>On a multi-core machine, the second version is significantly faster — that’s **parallelism** in action.</p><p>— -</p><p>## ⚠️ Common Beginner Mistakes</p><p>**1. Forgetting to wait for goroutines**<br>```go<br>// ❌ Bad — main exits before goroutine runs<br>go doSomething()</p><p>// ✅ Good — use WaitGroup or channel to wait<br>```</p><p>**2. Sharing memory without protection**<br>```go<br>// ❌ Bad — race condition!<br>counter := 0<br>go func() { counter++ }()<br>go func() { counter++ }()</p><p>// ✅ Good — use sync.Mutex or channels<br>var mu sync.Mutex<br>go func() { mu.Lock(); counter++; mu.Unlock() }()<br>```</p><p>**3. Thinking more goroutines = faster**</p><p>Goroutines are cheap (a few KB each), but spawning millions without control will hurt you. Use **worker pools** to limit concurrency.</p><p>— -</p><h3>🏁 The One-Line Summary</h3><p>&gt; **Concurrency** is how you *design* your program. **Parallelism** is what happens at *runtime* when the hardware allows it.</p><p>Go gives you the tools to write concurrent code elegantly — and its runtime takes care of parallelism for you.</p><p>Start with goroutines and channels. Keep it simple. The performance will follow.</p><p>— -</p><p>*Happy gophering! 🐹*</p><p>*If this helped you, drop a clap (or fifty) — it genuinely helps more beginners find it.*</p><p>— -</p><p>**Tags:** Go · Golang · Programming · Concurrency · Software Development</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a4a6c195951" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerize Any Laravel App in Minutes — With Sail and Without]]></title>
            <link>https://medium.com/@tanvirhossenbappy751/dockerize-any-laravel-app-in-minutes-with-sail-and-without-02e0697f0fbd?source=rss-d8f8c06b0a32------2</link>
            <guid isPermaLink="false">https://medium.com/p/02e0697f0fbd</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[laravel-sail]]></category>
            <category><![CDATA[laravel-framework]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Tanvir Hossen Bappy]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 11:47:07 GMT</pubDate>
            <atom:updated>2026-02-18T11:48:59.386Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vchtu8CGYmkxWXOK42zyg.png" /></figure><h3>A complete, battle-tested guide for fresh installs and existing projects — from zero to running containers</h3><p><em>5 min read · Laravel · Docker · DevOps · PHP · Web Development</em></p><p>You’ve built a Laravel app. It works perfectly on your machine. Then a teammate clones it, runs php artisan serve, and nothing works. Sound familiar?</p><p>This is the classic “works on my machine” problem — and Docker solves it permanently. In this guide, I’ll walk you through <strong>three complete setups</strong>: using Laravel Sail (the easy path), adding Sail to an existing project, and a fully custom Docker setup (the production-grade path).</p><p>By the end, you’ll have a reproducible, containerized Laravel environment that works on every machine, every time.</p><h3>Why Dockerize Your Laravel App?</h3><p>Before we dive in, here’s what you actually gain:</p><ul><li><strong>Consistency</strong> — identical environments across dev, staging, and production</li><li><strong>No more “install PHP on your machine”</strong> — everything runs in containers</li><li><strong>Team onboarding in minutes</strong> — clone, run one command, done</li><li><strong>Easy service management</strong> — MySQL, Redis, Mailpit — all in one docker-compose.yml</li><li><strong>Production-ready deployments</strong> — same container, different environment variables</li></ul><h3>Prerequisites</h3><p>Make sure Docker Desktop is installed and running.</p><pre>docker --version        # Should show 20.x or higher<br>docker compose version  # Should show v2.x<br>docker info             # Confirms Docker daemon is running</pre><p>Download Docker Desktop: <a href="https://docs.docker.com/get-docker/">docs.docker.com/get-docker</a></p><h3>Method 1: Laravel Sail — Fresh Project (The Easy Way)</h3><p>Laravel Sail is Laravel’s official Docker development environment. It’s the fastest way to get started.</p><h3>Create a new Laravel project</h3><p>The beauty of Sail is that you don’t even need PHP installed locally:</p><pre>curl -s &quot;https://laravel.build/my-app&quot; | bash<br>cd my-app</pre><p>Want specific services from day one? Pass them in the query string:</p><pre>curl -s &quot;https://laravel.build/my-app?with=mysql,redis,mailpit&quot; | bash</pre><p>Available services: mysql, pgsql, mariadb, redis, memcached, meilisearch, typesense, minio, selenium, mailpit</p><h3>Start your environment</h3><pre>./vendor/bin/sail up -d</pre><p>The -d flag runs containers in the background (detached mode). First run will pull Docker images and build — grab a coffee.</p><h3>Set up a Sail alias (highly recommended)</h3><p>Typing ./vendor/bin/sail every time gets old fast. Add this to your ~/.bashrc or ~/.zshrc:</p><pre>alias sail=&#39;sh $([ -f sail ] &amp;&amp; echo sail || echo vendor/bin/sail)&#39;<br>source ~/.bashrc</pre><p>Now you can just type sail instead of ./vendor/bin/sail.</p><h3>Configure and migrate</h3><pre>cp .env.example .env<br>sail artisan key:generate<br>sail artisan migrate<br>sail artisan db:seed</pre><p>Your .env database config should look like this (Sail&#39;s defaults):</p><pre>DB_HOST=mysql<br>DB_PORT=3306<br>DB_DATABASE=laravel<br>DB_USERNAME=sail<br>DB_PASSWORD=password</pre><blockquote><em>🔑 </em><strong><em>Critical:</em></strong><em> The </em><em>DB_HOST must be </em><em>mysql (the Docker service name), NOT </em><em>localhost. This is the #1 gotcha for beginners.</em></blockquote><p>Visit http://localhost — your app is live.</p><h3>Method 2: Laravel Sail — Existing Project</h3><p>Already have a Laravel project? Adding Sail takes under five minutes.</p><h3>Install Sail via Composer</h3><pre>cd your-existing-project<br>composer require laravel/sail --dev<br>php artisan sail:install</pre><p>An interactive menu will appear asking which services you want. Select them (e.g., 0 for MySQL, 1 for Redis) and Sail generates a docker-compose.yml tailored to your choices.</p><h3>Update your .env</h3><p>Change any localhost references to Docker service names:</p><pre>DB_HOST=mysql       # was: localhost<br>REDIS_HOST=redis    # was: localhost</pre><h3>Build and start</h3><pre>./vendor/bin/sail up -d --build<br>./vendor/bin/sail composer install<br>./vendor/bin/sail npm install<br>./vendor/bin/sail artisan migrate</pre><h3>Method 3: Custom Docker Setup — No Sail (Production-Grade)</h3><p>Sail is great for development, but for production you want full control. This setup gives you a multi-stage Dockerfile, Nginx, MySQL, Redis, phpMyAdmin, queue workers, and a cron scheduler — all wired together.</p><h3>Project structure</h3><pre>your-laravel-app/<br>├── docker/<br>│   ├── nginx/<br>│   │   └── default.conf<br>│   └── php/<br>│       └── php.ini<br>├── Dockerfile<br>├── docker-compose.yml<br>├── docker-compose.prod.yml<br>└── .dockerignore</pre><h3>Step 1: The Dockerfile (multi-stage)</h3><p>Multi-stage builds keep your production image lean by separating dev tooling from production artifacts:</p><pre># ── Stage 1: Base ──────────────────────────────────────────<br>FROM php:8.2-fpm AS base<br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    git curl libpng-dev libonig-dev libxml2-dev \<br>    libzip-dev zip unzip \<br>    &amp;&amp; apt-get clean &amp;&amp; rm -rf /var/lib/apt/lists/*<br>RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd zip<br>RUN pecl install redis &amp;&amp; docker-php-ext-enable redis<br>COPY --from=composer:latest /usr/bin/composer /usr/bin/composer<br>WORKDIR /var/www/html<br># ── Stage 2: Development ───────────────────────────────────<br>FROM base AS development<br>RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \<br>    &amp;&amp; apt-get install -y nodejs<br>COPY . .<br>RUN composer install --optimize-autoloader<br>RUN npm install<br>EXPOSE 9000<br>CMD [&quot;php-fpm&quot;]<br># ── Stage 3: Production ────────────────────────────────────<br>FROM base AS production<br>COPY . .<br>RUN composer install --no-dev --optimize-autoloader --no-interaction<br>RUN chown -R www-data:www-data storage bootstrap/cache \<br>    &amp;&amp; chmod -R 775 storage bootstrap/cache<br>RUN php artisan config:cache \<br>    &amp;&amp; php artisan route:cache \<br>    &amp;&amp; php artisan view:cache<br>EXPOSE 9000<br>CMD [&quot;php-fpm&quot;]</pre><h3>Step 2: docker-compose.yml</h3><pre>version: &#39;3.8&#39;<br>services:<br>  app:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>      target: development<br>    container_name: laravel_app<br>    restart: unless-stopped<br>    working_dir: /var/www/html<br>    volumes:<br>      - .:/var/www/html<br>      - ./docker/php/php.ini:/usr/local/etc/php/conf.d/custom.ini<br>    networks:<br>      - laravel_network<br>    depends_on:<br>      - mysql<br>      - redis<br>  nginx:<br>    image: nginx:alpine<br>    container_name: laravel_nginx<br>    restart: unless-stopped<br>    ports:<br>      - &quot;8080:80&quot;<br>    volumes:<br>      - .:/var/www/html<br>      - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf<br>    networks:<br>      - laravel_network<br>    depends_on:<br>      - app<br>  mysql:<br>    image: mysql:8.0<br>    container_name: laravel_mysql<br>    restart: unless-stopped<br>    environment:<br>      MYSQL_ROOT_PASSWORD: rootpassword<br>      MYSQL_DATABASE: laravel<br>      MYSQL_USER: laravel<br>      MYSQL_PASSWORD: password<br>    ports:<br>      - &quot;3306:3306&quot;<br>    volumes:<br>      - mysql_data:/var/lib/mysql<br>    networks:<br>      - laravel_network<br>  redis:<br>    image: redis:7-alpine<br>    container_name: laravel_redis<br>    restart: unless-stopped<br>    ports:<br>      - &quot;6379:6379&quot;<br>    volumes:<br>      - redis_data:/data<br>    networks:<br>      - laravel_network<br>  phpmyadmin:<br>    image: phpmyadmin/phpmyadmin<br>    container_name: laravel_phpmyadmin<br>    restart: unless-stopped<br>    ports:<br>      - &quot;8081:80&quot;<br>    environment:<br>      PMA_HOST: mysql<br>      MYSQL_ROOT_PASSWORD: rootpassword<br>    networks:<br>      - laravel_network<br>    depends_on:<br>      - mysql<br>volumes:<br>  mysql_data:<br>  redis_data:<br>networks:<br>  laravel_network:<br>    driver: bridge</pre><h3>Step 3: Nginx configuration</h3><p>Create docker/nginx/default.conf:</p><pre>server {<br>    listen 80;<br>    server_name localhost;<br>    root /var/www/html/public;<br>    index index.php index.html;<br>add_header X-Frame-Options &quot;SAMEORIGIN&quot;;<br>    add_header X-Content-Type-Options &quot;nosniff&quot;;<br>    charset utf-8;<br>    location / {<br>        try_files $uri $uri/ /index.php?$query_string;<br>    }<br>    error_page 404 /index.php;<br>    location ~ \.php$ {<br>        fastcgi_pass app:9000;<br>        fastcgi_index index.php;<br>        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;<br>        include fastcgi_params;<br>    }<br>    location ~ /\.(?!well-known).* {<br>        deny all;<br>    }<br>}</pre><h3>Step 4: PHP configuration</h3><p>Create docker/php/php.ini:</p><pre>upload_max_filesize = 64M<br>post_max_size = 64M<br>max_execution_time = 300<br>memory_limit = 256M<br>date.timezone = Asia/Dhaka</pre><h3>Step 5: .dockerignore</h3><pre>.git<br>node_modules<br>vendor<br>.env<br>storage/logs/*<br>storage/framework/cache/*<br>storage/framework/sessions/*<br>storage/framework/views/*<br>bootstrap/cache/*<br>*.log</pre><h3>Step 6: Update .env and launch</h3><pre># .env database settings<br>DB_CONNECTION=mysql<br>DB_HOST=mysql<br>DB_PORT=3306<br>DB_DATABASE=laravel<br>DB_USERNAME=laravel<br>DB_PASSWORD=password<br><br>REDIS_HOST=redis<br>REDIS_PORT=6379<br>CACHE_DRIVER=redis<br>SESSION_DRIVER=redis<br>QUEUE_CONNECTION=redis</pre><pre>docker compose build<br>docker compose up -d<br><br>docker compose exec app bash<br># Inside the container:<br>composer install<br>php artisan key:generate<br>php artisan migrate<br>php artisan storage:link</pre><h3>Production Setup: Queue Workers + Scheduler</h3><p>In production, add dedicated containers for your queue worker and task scheduler. Create docker-compose.prod.yml:</p><pre>version: &#39;3.8&#39;<br>services:<br>  # ... (app, nginx, mysql, redis from above, with target: production)<br>  queue:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>      target: production<br>    container_name: laravel_queue<br>    restart: always<br>    command: php artisan queue:work --sleep=3 --tries=3<br>    networks:<br>      - laravel_prod_network<br>    depends_on:<br>      - mysql<br>      - redis<br>  scheduler:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>      target: production<br>    container_name: laravel_scheduler<br>    restart: always<br>    command: bash -c &quot;while true; do php artisan schedule:run; sleep 60; done&quot;<br>    networks:<br>      - laravel_prod_network<br>    depends_on:<br>      - mysql</pre><p>Deploy to production:</p><pre>docker compose -f docker-compose.prod.yml up -d --build</pre><h3>Essential Commands Cheat Sheet</h3><h3>Docker Compose</h3><pre>docker compose up -d              # Start in background<br>docker compose up -d --build      # Rebuild and start<br>docker compose down               # Stop containers<br>docker compose down -v            # Stop and delete volumes<br>docker compose ps                 # Check container status<br>docker compose logs -f            # Stream all logs<br>docker compose logs -f app        # Stream app logs only<br>docker compose restart app        # Restart a specific service<br>docker compose build --no-cache   # Force fresh build</pre><h3>Entering containers</h3><pre>docker compose exec app bash              # App shell<br>docker compose exec mysql mysql -u root -p  # MySQL shell<br>docker compose exec redis redis-cli       # Redis CLI<br>docker compose exec nginx sh              # Nginx shell</pre><h3>Laravel Artisan (Docker)</h3><pre>docker compose exec app php artisan key:generate<br>docker compose exec app php artisan migrate<br>docker compose exec app php artisan migrate:fresh --seed<br>docker compose exec app php artisan cache:clear<br>docker compose exec app php artisan optimize:clear<br>docker compose exec app php artisan config:cache<br>docker compose exec app php artisan route:cache<br>docker compose exec app php artisan storage:link<br>docker compose exec app php artisan queue:work<br>docker compose exec app php artisan route:list<br>docker compose exec app php artisan tinker</pre><h3>Laravel Artisan (Sail)</h3><pre>sail artisan key:generate<br>sail artisan migrate<br>sail artisan migrate:fresh --seed<br>sail artisan cache:clear<br>sail artisan optimize:clear<br>sail artisan make:controller UserController<br>sail artisan make:model Post -m<br>sail artisan tinker</pre><h3>Composer &amp; NPM (Docker)</h3><pre>docker compose exec app composer install<br>docker compose exec app composer require vendor/package<br>docker compose exec app composer update<br>docker compose exec app npm install<br>docker compose exec app npm run build<br>docker compose exec app npm run dev</pre><h3>Composer &amp; NPM (Sail)</h3><pre>sail composer install<br>sail composer require vendor/package<br>sail npm install<br>sail npm run build<br>sail npm run dev</pre><h3>Sail-specific</h3><pre>sail up -d<br>sail down<br>sail shell          # Enter app container<br>sail root-shell     # Enter as root<br>sail mysql          # MySQL shell<br>sail redis          # Redis CLI<br>sail test           # Run PHPUnit tests<br>sail share          # Expose to internet via Expose<br>sail build --no-cache</pre><h3>Monitoring</h3><pre>docker stats                        # Resource usage (all)<br>docker stats laravel_app            # Resource usage (specific)<br>docker logs laravel_app             # Container logs<br>docker logs --tail=100 laravel_app  # Last 100 log lines<br>docker logs -f laravel_app          # Follow logs<br>docker top laravel_app              # Running processes<br>docker inspect laravel_app          # Full container details<br>docker system df                    # Disk usage</pre><h3>Cleanup</h3><pre>docker container prune              # Remove stopped containers<br>docker image prune                  # Remove unused images<br>docker volume prune                 # Remove unused volumes<br>docker system prune                 # Clean everything unused<br>docker system prune -a --volumes    # Nuclear option ⚠️<br>docker rmi image_name:tag           # Remove specific image<br>docker rm container_name            # Remove specific container<br>docker volume rm volume_name        # Remove specific volume</pre><h3>Default Service URLs</h3><p>Service URL Laravel App <a href="http://localhost:8080/">http://localhost:8080</a> phpMyAdmin <a href="http://localhost:8081/">http://localhost:8081</a> Mailpit (Sail) <a href="http://localhost:8025/">http://localhost:8025</a> Minio (Sail) <a href="http://localhost:9000/">http://localhost:9000</a></p><h3>Troubleshooting the Most Common Issues</h3><p><strong>Permission denied on storage:</strong></p><pre>docker compose exec app chown -R www-data:www-data storage bootstrap/cache<br>docker compose exec app chmod -R 775 storage bootstrap/cache</pre><p><strong>Database won’t connect:</strong> Make sure DB_HOST=mysql in .env — not localhost. Verify the MySQL container is running with docker compose ps.</p><p><strong>Port already in use:</strong></p><pre># Mac/Linux<br>sudo lsof -i :8080<br># Windows<br>netstat -ano | findstr :8080</pre><p>Change the port in docker-compose.yml from &quot;8080:80&quot; to something else like &quot;8090:80&quot;.</p><p><strong>Container won’t start:</strong></p><pre>docker compose logs app   # Check what the error is<br>docker compose build --no-cache &amp;&amp; docker compose up -d</pre><h3>Wrapping Up</h3><p>Docker transforms Laravel development from a fragile, machine-specific setup into a reproducible, shareable environment. Whether you pick Sail for its simplicity or build a custom stack for production control, the workflow is the same: define your services, declare your dependencies, and let Docker handle the rest.</p><p>The most important thing to remember: <strong>DB_HOST is always the service name</strong> (like mysql), never localhost — inside Docker&#39;s network, services find each other by name.</p><p>Start with Sail. Graduate to custom Docker when you need more control. Your future self — and your teammates — will thank you.</p><p><em>Found this useful? Give it a clap 👏 and share it with your team. Got questions or a setup that’s different? Drop it in the comments — happy to help.</em></p><p><strong>Tags:</strong> Laravel Docker PHP DevOps Web Development Backend Programming Software Engineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02e0697f0fbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge Your Laravel App with FrankenPHP and Docker: A Complete Setup Guide]]></title>
            <link>https://medium.com/@tanvirhossenbappy751/supercharge-your-laravel-app-with-frankenphp-and-docker-a-complete-setup-guide-de0980d61e05?source=rss-d8f8c06b0a32------2</link>
            <guid isPermaLink="false">https://medium.com/p/de0980d61e05</guid>
            <category><![CDATA[frankenphp]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[laravel-development]]></category>
            <dc:creator><![CDATA[Tanvir Hossen Bappy]]></dc:creator>
            <pubDate>Tue, 17 Feb 2026 11:08:11 GMT</pubDate>
            <atom:updated>2026-02-17T11:08:11.658Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop using Nginx + PHP-FPM. There’s a faster, simpler way.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kmpLW_1wjzTK6WTCVO_F-g.png" /></figure><p>If you’ve been running Laravel with the classic Nginx + PHP-FPM combo, you already know the drill — multiple config files, separate processes, and a setup that works but never feels quite right. What if you could replace all of that with a single binary that’s faster, simpler, and comes with automatic HTTPS baked in?</p><p>Meet <strong>FrankenPHP</strong>.</p><p>In this guide, I’ll walk you through setting up a production-ready Laravel application using FrankenPHP inside Docker — from a blank folder to a fully running app with MySQL, Redis, queue workers, and a scheduled task runner, all in one container.</p><h3>What Is FrankenPHP?</h3><p>FrankenPHP is a modern PHP application server built on top of <a href="https://caddyserver.com/">Caddy</a>, written in Go. It was created by <a href="https://dunglas.dev/">Kévin Dunglas</a>, the person behind API Platform, and it fundamentally changes how PHP runs.</p><p>Instead of the traditional model where every request spins up a new PHP process, FrankenPHP supports <strong>Worker Mode</strong> — PHP bootstraps once and stays resident in memory, handling thousands of requests without restarting. Think of it like how Node.js works, but for PHP.</p><p><strong>What makes it stand out:</strong></p><ul><li>⚡ <strong>Worker Mode</strong> — PHP stays alive between requests, dramatically reducing boot time overhead</li><li>🔒 <strong>Automatic HTTPS</strong> — Caddy handles Let’s Encrypt certificates for you, zero configuration</li><li>🌐 <strong>HTTP/3 + Early Hints</strong> — modern protocol support out of the box</li><li>📦 <strong>Single binary</strong> — no Nginx, no PHP-FPM, no separate web server config</li><li>🧵 <strong>Built on Go</strong> — true concurrency via goroutines</li></ul><h3>The Stack We’re Building</h3><p>Service Image Role <strong>App</strong> dunglas/frankenphp:latest-php8.3-alpine Laravel + Web Server <strong>MySQL</strong> mysql:8.0 Primary Database <strong>Redis</strong> redis:7-alpine Cache, Sessions, Queues</p><p>All managed with Docker Compose, with optional phpMyAdmin and Redis Commander for local development.</p><h3>Prerequisites</h3><ul><li>Docker Desktop with WSL 2 backend (Windows) or Docker Engine (Linux/macOS)</li><li>Basic familiarity with Laravel and the command line</li></ul><blockquote><strong><em>Windows users:</em></strong><em> Always work inside WSL (Ubuntu), not PowerShell. Store your project under </em><em>/home/username/ — not </em><em>/mnt/c/ — to avoid serious performance issues.</em></blockquote><h3>Project Structure</h3><p>Before we dive into code, here’s what we’re building:</p><pre>my-laravel-app/<br>├── docker/<br>│   ├── frankenphp/<br>│   │   ├── Dockerfile<br>│   │   ├── Caddyfile          ← The web server config<br>│   │   ├── entrypoint.sh      ← Startup logic<br>│   │   └── supervisord.conf   ← Process manager<br>│   └── mysql/<br>│       └── init.sql<br>├── docker-compose.yml<br>├── .env.example<br>└── ... (Laravel files)</pre><h3>Step 1: The Dockerfile</h3><pre>FROM dunglas/frankenphp:latest-php8.3-alpine<br><br>LABEL maintainer=&quot;Your Name &lt;you@example.com&gt;&quot;<br><br># Install system dependencies<br>RUN apk add --no-cache \<br>    git \<br>    curl \<br>    bash \<br>    libpng-dev \<br>    libjpeg-turbo-dev \<br>    libwebp-dev \<br>    freetype-dev \<br>    icu-dev \<br>    libzip-dev \<br>    oniguruma-dev \<br>    zip \<br>    unzip \<br>    nodejs \<br>    npm \<br>    mysql-client \<br>    supervisor<br><br># Install PHP extensions<br>RUN install-php-extensions \<br>    pdo_mysql \<br>    mbstring \<br>    exif \<br>    pcntl \<br>    bcmath \<br>    gd \<br>    intl \<br>    zip \<br>    opcache \<br>    redis \<br>    @composer<br><br># Configure OPcache for production<br>RUN echo &quot;opcache.enable=1&quot; &gt;&gt; /usr/local/etc/php/conf.d/opcache.ini \<br>    &amp;&amp; echo &quot;opcache.memory_consumption=256&quot; &gt;&gt; /usr/local/etc/php/conf.d/opcache.ini \<br>    &amp;&amp; echo &quot;opcache.interned_strings_buffer=16&quot; &gt;&gt; /usr/local/etc/php/conf.d/opcache.ini \<br>    &amp;&amp; echo &quot;opcache.max_accelerated_files=20000&quot; &gt;&gt; /usr/local/etc/php/conf.d/opcache.ini \<br>    &amp;&amp; echo &quot;opcache.revalidate_freq=0&quot; &gt;&gt; /usr/local/etc/php/conf.d/opcache.ini \<br>    &amp;&amp; echo &quot;opcache.save_comments=1&quot; &gt;&gt; /usr/local/etc/php/conf.d/opcache.ini<br><br># Set working directory<br>WORKDIR /app<br><br># Copy composer files first (for layer caching)<br>COPY composer.json composer.lock* ./<br><br># Install PHP dependencies<br>RUN composer install --no-dev --optimize-autoloader --no-scripts --no-interaction 2&gt;/dev/null || true<br><br># Copy the rest of the application<br>COPY . .<br><br># Set permissions<br>RUN mkdir -p /var/log/supervisor /var/run<br>RUN chown -R www-data:www-data /app \<br>    &amp;&amp; chmod -R 755 /app/storage \<br>    &amp;&amp; chmod -R 755 /app/bootstrap/cache<br><br># Copy Caddyfile<br>COPY docker/frankenphp/Caddyfile /etc/caddy/Caddyfile<br><br># Copy supervisor config<br>COPY docker/frankenphp/supervisord.conf /etc/supervisor/conf.d/supervisord.conf<br><br># Copy entrypoint script<br>COPY docker/frankenphp/entrypoint.sh /usr/local/bin/entrypoint.sh<br>RUN chmod +x /usr/local/bin/entrypoint.sh<br><br>EXPOSE 80 443 443/udp<br><br>ENTRYPOINT [&quot;/usr/local/bin/entrypoint.sh&quot;]<br>CMD [&quot;supervisord&quot;, &quot;-c&quot;, &quot;/etc/supervisor/conf.d/supervisord.conf&quot;]<br></pre><p>Nothing surprising here — we install PHP extensions, copy the app, and wire up our config files. The install-php-extensions helper from the FrankenPHP base image makes extension installation painless.</p><h3>Step 2: The Caddyfile</h3><p>This is the most important file to get right. Here’s the gotcha that trips almost everyone up the first time:</p><p><strong>This will fail:</strong></p><pre>{<br>    frankenphp<br>    auto_https off<br>}:80 {<br>    root * /app/public<br>    php_server   ← ERROR: not an ordered HTTP handler<br>}<br></pre><p><strong>This works:</strong></p><pre>{<br>    frankenphp<br>    auto_https off<br>    order php_server before file_server   ← This line is mandatory<br>}<br><br>:80 {<br>    root * /app/public<br>    php_server<br>}</pre><p>The order php_server before file_server directive in the global block tells Caddy where php_server fits in the middleware chain. Without it, you&#39;ll get:</p><pre>Error: directive &#39;php_server&#39; is not an ordered HTTP handler,<br>so it cannot be used here</pre><p>For production, simply remove auto_https off and Caddy will automatically obtain and renew SSL certificates from Let&#39;s Encrypt.</p><h3>Step 3: The Entrypoint Script</h3><p>The entrypoint script handles all the startup logic — waiting for MySQL, running migrations, and setting permissions.</p><p>One important detail: the default approach of using mysql-client to check database readiness often fails because the binary isn&#39;t available or configured. Using PHP&#39;s PDO directly is more reliable:</p><pre>#!/bin/bash<br>set -e<br>echo &quot;🚀 Starting Laravel + FrankenPHP...&quot;<br>if [ -n &quot;$DB_HOST&quot; ]; then<br>    echo &quot;⏳ Waiting for MySQL at $DB_HOST:${DB_PORT:-3306}...&quot;<br>    until php -r &quot;<br>        try {<br>            \$pdo = new PDO(<br>                &#39;mysql:host=${DB_HOST};port=${DB_PORT:-3306};dbname=${DB_DATABASE}&#39;,<br>                &#39;${DB_USERNAME}&#39;,<br>                &#39;${DB_PASSWORD}&#39;<br>            );<br>            exit(0);<br>        } catch (Exception \$e) {<br>            exit(1);<br>        }<br>    &quot; 2&gt;/dev/null; do<br>        echo &quot;   MySQL not ready, retrying in 2s...&quot;<br>        sleep 2<br>    done<br>    echo &quot;✅ MySQL is ready!&quot;<br>fi<br>cd /app<br>if [ ! -d &quot;vendor&quot; ]; then<br>    composer install --optimize-autoloader --no-interaction<br>fi<br>if [ -z &quot;$APP_KEY&quot; ] || [ &quot;$APP_KEY&quot; = &quot;base64:&quot; ]; then<br>    php artisan key:generate --force<br>fi<br>if [ &quot;${RUN_MIGRATIONS:-true}&quot; = &quot;true&quot; ]; then<br>    php artisan migrate --force<br>fi<br>chown -R www-data:www-data /app/storage /app/bootstrap/cache<br>chmod -R 775 /app/storage /app/bootstrap/cache<br>echo &quot;✅ Laravel setup complete. Starting server...&quot;<br>exec &quot;$@&quot;</pre><h3>Step 4: Supervisor — One Container, Multiple Processes</h3><p>Instead of running separate containers for the queue worker and scheduler, we use Supervisor to manage all processes inside a single app container:</p><pre>[supervisord]<br>nodaemon=true<br>user=root<br>[program:frankenphp]<br>command=frankenphp run --config /etc/caddy/Caddyfile<br>directory=/app<br>autostart=true<br>autorestart=true<br>stdout_logfile=/dev/stdout<br>stdout_logfile_maxbytes=0<br>stderr_logfile=/dev/stderr<br>stderr_logfile_maxbytes=0<br>[program:laravel-worker]<br>command=php /app/artisan queue:work --sleep=3 --tries=3 --max-time=3600<br>directory=/app<br>autostart=true<br>autorestart=true<br>numprocs=2<br>process_name=%(program_name)s_%(process_num)02d<br>stdout_logfile=/dev/stdout<br>stdout_logfile_maxbytes=0<br>[program:laravel-scheduler]<br>command=bash -c &quot;while true; do php /app/artisan schedule:run --verbose --no-interaction &amp; sleep 60; done&quot;<br>directory=/app<br>autostart=true<br>autorestart=true<br>stdout_logfile=/dev/stdout<br>stdout_logfile_maxbytes=0</pre><p>This gives you the web server, two queue workers, and the scheduler all running in one container — perfect for keeping things simple without sacrificing functionality.</p><h3>Step 5: Docker Compose</h3><pre>services:<br><br>  # ─────────────────────────────────────────<br>  # Laravel App (FrankenPHP)<br>  # ─────────────────────────────────────────<br>  app:<br>    build:<br>      context: .<br>      dockerfile: docker/frankenphp/Dockerfile<br>    container_name: laravel_app<br>    restart: unless-stopped<br>    ports:<br>      - &quot;${APP_PORT:-80}:80&quot;<br>      - &quot;${APP_PORT_HTTPS:-443}:443&quot;<br>      - &quot;${APP_PORT_HTTPS:-443}:443/udp&quot;  # HTTP/3 support<br>    environment:<br>      APP_ENV: &quot;${APP_ENV:-local}&quot;<br>      APP_KEY: &quot;${APP_KEY}&quot;<br>      APP_DEBUG: &quot;${APP_DEBUG:-true}&quot;<br>      APP_URL: &quot;${APP_URL:-http://localhost}&quot;<br><br>      DB_CONNECTION: mysql<br>      DB_HOST: mysql<br>      DB_PORT: 3306<br>      DB_DATABASE: &quot;${DB_DATABASE:-laravel}&quot;<br>      DB_USERNAME: &quot;${DB_USERNAME:-laravel}&quot;<br>      DB_PASSWORD: &quot;${DB_PASSWORD:-secret}&quot;<br><br>      REDIS_HOST: redis<br>      REDIS_PORT: 6379<br><br>      CACHE_DRIVER: redis<br>      SESSION_DRIVER: redis<br>      QUEUE_CONNECTION: redis<br><br>      RUN_MIGRATIONS: &quot;${RUN_MIGRATIONS:-true}&quot;<br>    volumes:<br>      - .:/app<br>      - /app/vendor           # Exclude vendor from bind mount<br>      - /app/node_modules     # Exclude node_modules from bind mount<br>      - app_storage:/app/storage<br>    depends_on:<br>      mysql:<br>        condition: service_healthy<br>      redis:<br>        condition: service_healthy<br>    networks:<br>      - laravel<br><br>  # ─────────────────────────────────────────<br>  # MySQL Database<br>  # ─────────────────────────────────────────<br>  mysql:<br>    image: mysql:8.0<br>    container_name: laravel_mysql<br>    restart: unless-stopped<br>    environment:<br>      MYSQL_ROOT_PASSWORD: &quot;${DB_ROOT_PASSWORD:-rootsecret}&quot;<br>      MYSQL_DATABASE: &quot;${DB_DATABASE:-laravel}&quot;<br>      MYSQL_USER: &quot;${DB_USERNAME:-laravel}&quot;<br>      MYSQL_PASSWORD: &quot;${DB_PASSWORD:-secret}&quot;<br>    ports:<br>      - &quot;${FORWARD_DB_PORT:-3306}:3306&quot;<br>    volumes:<br>      - mysql_data:/var/lib/mysql<br>      - ./docker/mysql/init.sql:/docker-entrypoint-initdb.d/init.sql:ro<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;mysqladmin&quot;, &quot;ping&quot;, &quot;-h&quot;, &quot;localhost&quot;, &quot;-u&quot;, &quot;root&quot;, &quot;-p${DB_ROOT_PASSWORD:-rootsecret}&quot;]<br>      interval: 10s<br>      timeout: 5s<br>      retries: 10<br>      start_period: 30s<br>    networks:<br>      - laravel<br><br>  # ─────────────────────────────────────────<br>  # Redis Cache &amp; Queue<br>  # ─────────────────────────────────────────<br>  redis:<br>    image: redis:7-alpine<br>    container_name: laravel_redis<br>    restart: unless-stopped<br>    command: redis-server --appendonly yes<br>    ports:<br>      - &quot;${FORWARD_REDIS_PORT:-6379}:6379&quot;<br>    volumes:<br>      - redis_data:/data<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;redis-cli&quot;, &quot;ping&quot;]<br>      interval: 10s<br>      timeout: 5s<br>      retries: 5<br>    networks:<br>      - laravel<br><br>  # ─────────────────────────────────────────<br>  # phpMyAdmin (optional, dev only)<br>  # ─────────────────────────────────────────<br>  phpmyadmin:<br>    image: phpmyadmin:latest<br>    container_name: laravel_phpmyadmin<br>    restart: unless-stopped<br>    environment:<br>      PMA_HOST: mysql<br>      PMA_USER: root<br>      PMA_PASSWORD: &quot;${DB_ROOT_PASSWORD:-rootsecret}&quot;<br>      UPLOAD_LIMIT: 64M<br>    ports:<br>      - &quot;${PHPMYADMIN_PORT:-8080}:80&quot;<br>    depends_on:<br>      mysql:<br>        condition: service_healthy<br>    networks:<br>      - laravel<br>    profiles:<br>      - dev<br><br>  # ─────────────────────────────────────────<br>  # Redis Commander (optional, dev only)<br>  # ─────────────────────────────────────────<br>  redis-commander:<br>    image: rediscommander/redis-commander:latest<br>    container_name: laravel_redis_commander<br>    restart: unless-stopped<br>    environment:<br>      REDIS_HOSTS: &quot;local:redis:6379&quot;<br>    ports:<br>      - &quot;${REDIS_COMMANDER_PORT:-8081}:8081&quot;<br>    depends_on:<br>      redis:<br>        condition: service_healthy<br>    networks:<br>      - laravel<br>    profiles:<br>      - dev<br><br># ─────────────────────────────────────────<br># Volumes<br># ─────────────────────────────────────────<br>volumes:<br>  mysql_data:<br>    driver: local<br>  redis_data:<br>    driver: local<br>  app_storage:<br>    driver: local<br><br># ─────────────────────────────────────────<br># Networks<br># ─────────────────────────────────────────<br>networks:<br>  laravel:<br>    driver: bridge Notice command: redis-server --appendonly yes — no --requirepass flag. Adding a password here without properly configuring it in your .env will give you the NOAUTH Authentication required error that many people stumble on.</pre><h3>Step 6: Environment Setup</h3><pre>cp .env.example .env</pre><p>Key values to confirm in your .env:</p><pre>DB_HOST=mysql<br>DB_DATABASE=laravel<br>DB_USERNAME=laravel<br>DB_PASSWORD=secret<br><br>REDIS_HOST=redis<br>REDIS_PASSWORD=        ← Leave empty, not &quot;null&quot;<br>REDIS_PORT=6379<br>CACHE_DRIVER=redis<br>SESSION_DRIVER=redis<br>QUEUE_CONNECTION=redis</pre><blockquote><strong><em>Important:</em></strong><em> Set </em><em>REDIS_PASSWORD= (empty), not </em><em>REDIS_PASSWORD=null. The string </em><em>&quot;null&quot; is not null in PHP — it&#39;s the literal string &quot;null&quot;, which will cause authentication failures.</em></blockquote><h3>Step 7: Install Laravel and Launch</h3><p>If you’re starting fresh, use Docker to run Composer without installing anything locally:</p><pre># Install into a temp folder first (current dir must be empty-ish)<br>docker run --rm \<br>  -v $(pwd):/app \<br>  -w /app \<br>  composer:latest \<br>  composer create-project laravel/laravel temp --prefer-dist</pre><pre># Move files out and clean up<br>cp -r temp/. .<br>sudo rm -rf temp    # sudo required — Docker writes as root</pre><p>Then clear the bootstrap cache before building (prevents the PailServiceProvider not found issue in Laravel 11):</p><pre>rm -f bootstrap/cache/packages.php<br>rm -f bootstrap/cache/services.php</pre><p>Now build and start:</p><pre>docker compose up -d --build</pre><p>Watch the logs:</p><pre>docker compose logs -f app</pre><p>You should see:</p><pre>✅ MySQL is ready!<br>✅ Laravel setup complete. Starting server...<br>{&quot;msg&quot;:&quot;FrankenPHP started 🐘&quot;,&quot;php_version&quot;:&quot;8.3.x&quot;}<br>{&quot;msg&quot;:&quot;server running&quot;,&quot;name&quot;:&quot;srv0&quot;,&quot;protocols&quot;:[&quot;h1&quot;,&quot;h2&quot;,&quot;h3&quot;]}</pre><p>Visit http://localhost — you&#39;re live. 🎉</p><h3>Working With the Running Container</h3><p>Once everything is up, jump into the container to run Artisan commands directly:</p><pre>docker compose exec app bash</pre><p>Now your terminal is inside the container and you can use Laravel naturally:</p><pre>php artisan migrate<br>php artisan make:model Post -mcr<br>php artisan route:list<br>php artisan tinker<br>composer require spatie/laravel-permission</pre><p>No more prefixing every command with docker compose exec app.</p><h3>Common Pitfalls and How to Avoid Them</h3><h3>1. The Caddyfile php_server error</h3><p>Always include order php_server before file_server in the global Caddy block.</p><h3>2. Redis NOAUTH</h3><p>Don’t add --requirepass to the Redis command in Compose unless you also configure it correctly in .env. The simplest fix: omit the password entirely in development.</p><h3>3. Vendor directory missing</h3><p>If you see require(/app/vendor/autoload.php): Failed to open stream, run:</p><pre>docker compose exec app composer install</pre><h3>4. Permission denied on rm -rf</h3><p>Docker creates files as root inside containers. Use sudo rm -rf when cleaning up from the host.</p><h3>5. The supervisord log directory missing</h3><p>Add RUN mkdir -p /var/log/supervisor /var/run to your Dockerfile before any chown commands.</p><h3>6. Laravel Pail ServiceProvider not found</h3><p>Clear the bootstrap cache before building:</p><pre>rm -f bootstrap/cache/packages.php bootstrap/cache/services.php</pre><h3>Going to Production</h3><p>Three changes for production:</p><p><strong>1. Remove </strong><strong>auto_https off from your Caddyfile</strong> — Caddy will handle SSL automatically.</p><p><strong>2. Update </strong><strong>.env:</strong></p><pre>APP_ENV=production<br>APP_DEBUG=false<br>APP_URL=https://yourdomain.com</pre><p><strong>3. Warm the caches after deploying:</strong></p><pre>docker compose exec app php artisan config:cache<br>docker compose exec app php artisan route:cache<br>docker compose exec app php artisan view:cache</pre><p>That’s it. No Certbot, no cron jobs for renewals, no separate SSL configuration.</p><h3>Wrapping Up</h3><p>FrankenPHP is a genuine step forward for PHP application serving. The combination of Worker Mode, automatic HTTPS, HTTP/3 support, and a dramatically simpler setup makes it worth adopting — especially for new projects.</p><p>The full setup we built today gives you:</p><ul><li>✅ A production-ready Laravel application</li><li>✅ Automatic database migrations on container start</li><li>✅ Queue workers and task scheduler running out of the box</li><li>✅ Redis for caching, sessions, and queues</li><li>✅ One command to start everything: docker compose up -d</li></ul><p>The configuration files for this setup are available on GitHub. If you run into any issues, the troubleshooting section above covers the most common ones based on real-world experience.</p><p><em>If this guide helped you, consider giving it a clap on Medium. Have a question or found an issue? Drop it in the comments.</em></p><p><strong>Tags:</strong> PHP Laravel Docker FrankenPHP Web Development DevOps Backend</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de0980d61e05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel AI SDK: The Complete Guide to Building Intelligent Applications]]></title>
            <link>https://medium.com/@tanvirhossenbappy751/laravel-ai-sdk-the-complete-guide-to-building-intelligent-applications-1c5fc86a1be4?source=rss-d8f8c06b0a32------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c5fc86a1be4</guid>
            <category><![CDATA[laravel-ai-tools]]></category>
            <category><![CDATA[laravel-framework]]></category>
            <category><![CDATA[ai-laravel]]></category>
            <category><![CDATA[ai-sdk]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Tanvir Hossen Bappy]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 07:44:32 GMT</pubDate>
            <atom:updated>2026-02-08T07:44:32.918Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction: Laravel Meets AI</h3><p>On February 5, 2026, Laravel released something revolutionary — the Laravel AI SDK. This isn’t just another package; it’s Laravel’s answer to the AI revolution, providing a clean, framework-native way to integrate AI capabilities into your applications.</p><p>If you’ve ever wanted to add AI features to your Laravel app but felt overwhelmed by different providers, complex APIs, and vendor lock-in, this is for you.</p><h3>What Makes Laravel AI SDK Special?</h3><h3>1. Multi-Provider Support</h3><p>Switch between Anthropic Claude, OpenAI, Google Gemini, and others with a single line of code. No more rewriting your entire codebase when you want to try a different AI provider.</p><pre>// Use Anthropic<br>$response = Ai::driver(&#39;anthropic&#39;)-&gt;generate(&#39;Explain Laravel routing&#39;);<br>// Switch to OpenAI<br>$response = Ai::driver(&#39;openai&#39;)-&gt;generate(&#39;Explain Laravel routing&#39;);<br>// Use Gemini<br>$response = Ai::driver(&#39;gemini&#39;)-&gt;generate(&#39;Explain Laravel routing&#39;);</pre><h3>2. Smart Fallbacks</h3><p>The SDK handles rate limits and outages automatically. If one provider fails, it seamlessly switches to another.</p><pre>// config/ai.php<br>&#39;fallbacks&#39; =&gt; [<br>    &#39;anthropic&#39; =&gt; [&#39;openai&#39;, &#39;gemini&#39;],<br>    &#39;openai&#39; =&gt; [&#39;anthropic&#39;],<br>],</pre><p>Now your application keeps running even when a provider goes down.</p><h3>3. All-in-One Package</h3><p>One SDK handles:</p><ul><li>Text generation</li><li>Image generation</li><li>Audio transcription</li><li>Text-to-speech</li><li>Embeddings</li><li>Vector search</li><li>Web search</li><li>File processing</li><li>Function calling</li></ul><h3>Feature Deep Dive with Real-World Examples</h3><h3>Feature 1: Text Generation — The Foundation</h3><p><strong>When to Use:</strong></p><ul><li>Product descriptions</li><li>Blog post summaries</li><li>Email drafts</li><li>Content translation</li></ul><p><strong>Example: E-commerce Product Description Generator</strong></p><pre>namespace App\Services;<br>use Laravel\Ai\Facades\Ai;<br>class ProductDescriptionService<br>{<br>    public function generateDescription(array $productData)<br>    {<br>        $prompt = &quot;Generate a compelling product description for:\n&quot;<br>            . &quot;Name: {$productData[&#39;name&#39;]}\n&quot;<br>            . &quot;Price: \${$productData[&#39;price&#39;]}\n&quot;<br>            . &quot;Category: {$productData[&#39;category&#39;]}\n&quot;<br>            . &quot;Features: &quot; . implode(&#39;, &#39;, $productData[&#39;features&#39;]);<br>        <br>        $response = Ai::systemPrompt(&#39;You are an expert e-commerce copywriter.&#39;)<br>            -&gt;temperature(0.8) // Higher creativity<br>            -&gt;maxTokens(200)<br>            -&gt;generate($prompt);<br>        <br>        return $response-&gt;text;<br>    }<br>}<br>// Usage<br>$service = new ProductDescriptionService();<br>$description = $service-&gt;generateDescription([<br>    &#39;name&#39; =&gt; &#39;Wireless Noise-Cancelling Headphones&#39;,<br>    &#39;price&#39; =&gt; 299,<br>    &#39;category&#39; =&gt; &#39;Audio&#39;,<br>    &#39;features&#39; =&gt; [&#39;40-hour battery&#39;, &#39;Active noise cancellation&#39;, &#39;Premium sound&#39;]<br>]);</pre><p><strong>Bilingual Example (Bangla):</strong></p><pre>namespace App\Services;<br>use Laravel\Ai\Facades\Ai;<br>class BanglaContentService<br>{<br>    public function generateBlogSummary(string $content)<br>    {<br>        $summary = Ai::systemPrompt(&#39;তুমি একজন দক্ষ বাংলা কন্টেন্ট রাইটার। সংক্ষিপ্ত সামারি লিখবে।&#39;)<br>            -&gt;generate(&quot;এই আর্টিকেলের সামারি লিখুন:\n\n{$content}&quot;);<br>        <br>        return $summary-&gt;text;<br>    }<br>}</pre><h3>Feature 2: Chat Conversations — Building Intelligent Assistants</h3><p><strong>When to Use:</strong></p><ul><li>Customer support bots</li><li>Shopping assistants</li><li>Educational tutors</li><li>Interactive help systems</li></ul><p><strong>Example: Customer Support Chatbot with Memory</strong></p><pre>namespace App\Http\Controllers;<br>use Illuminate\Http\Request;<br>use Laravel\Ai\Facades\Ai;<br>class CustomerSupportController extends Controller<br>{<br>    public function chat(Request $request)<br>    {<br>        // Retrieve conversation history<br>        $messages = session(&#39;chat_history&#39;, []);<br>        <br>        // Add user message<br>        $messages[] = [<br>            &#39;role&#39; =&gt; &#39;user&#39;, <br>            &#39;content&#39; =&gt; $request-&gt;input(&#39;message&#39;)<br>        ];<br>        <br>        // Get AI response with context<br>        $response = Ai::systemPrompt(<br>            &#39;You are a helpful customer support agent for TechShop, <br>             an electronics retailer. Be friendly, professional, and solution-oriented.&#39;<br>        )<br>        -&gt;chat($messages)<br>        -&gt;generate();<br>        <br>        // Add assistant response<br>        $messages[] = [<br>            &#39;role&#39; =&gt; &#39;assistant&#39;, <br>            &#39;content&#39; =&gt; $response-&gt;text<br>        ];<br>        <br>        // Save conversation<br>        session([&#39;chat_history&#39; =&gt; $messages]);<br>        <br>        return response()-&gt;json([<br>            &#39;reply&#39; =&gt; $response-&gt;text,<br>            &#39;conversation_id&#39; =&gt; session()-&gt;getId()<br>        ]);<br>    }<br>    <br>    public function resetChat()<br>    {<br>        session()-&gt;forget(&#39;chat_history&#39;);<br>        return response()-&gt;json([&#39;message&#39; =&gt; &#39;Chat reset successfully&#39;]);<br>    }<br>}</pre><p><strong>Livewire Real-Time Chat Component:</strong></p><pre>namespace App\Livewire;<br>use Livewire\Component;<br>use Laravel\Ai\Facades\Ai;<br>class AiChatWidget extends Component<br>{<br>    public $messages = [];<br>    public $input = &#39;&#39;;<br>    public $isTyping = false;<br>    <br>    public function mount()<br>    {<br>        $this-&gt;messages[] = [<br>            &#39;role&#39; =&gt; &#39;assistant&#39;,<br>            &#39;content&#39; =&gt; &#39;Hello! How can I help you today?&#39;<br>        ];<br>    }<br>    <br>    public function sendMessage()<br>    {<br>        if (empty($this-&gt;input)) return;<br>        <br>        // Add user message<br>        $this-&gt;messages[] = [<br>            &#39;role&#39; =&gt; &#39;user&#39;,<br>            &#39;content&#39; =&gt; $this-&gt;input<br>        ];<br>        <br>        $this-&gt;input = &#39;&#39;;<br>        $this-&gt;isTyping = true;<br>        <br>        // Get AI response<br>        $response = Ai::systemPrompt(&#39;You are a helpful assistant.&#39;)<br>            -&gt;chat($this-&gt;messages)<br>            -&gt;generate();<br>        <br>        // Add AI response<br>        $this-&gt;messages[] = [<br>            &#39;role&#39; =&gt; &#39;assistant&#39;,<br>            &#39;content&#39; =&gt; $response-&gt;text<br>        ];<br>        <br>        $this-&gt;isTyping = false;<br>    }<br>    <br>    public function render()<br>    {<br>        return view(&#39;livewire.ai-chat-widget&#39;);<br>    }<br>}</pre><p><strong>Blade Template:</strong></p><pre>&lt;div class=&quot;chat-container&quot;&gt;<br>    &lt;div class=&quot;messages&quot;&gt;<br>        @foreach($messages as $message)<br>            &lt;div class=&quot;message {{ $message[&#39;role&#39;] }}&quot;&gt;<br>                {{ $message[&#39;content&#39;] }}<br>            &lt;/div&gt;<br>        @endforeach<br>        <br>        @if($isTyping)<br>            &lt;div class=&quot;typing-indicator&quot;&gt;AI is typing...&lt;/div&gt;<br>        @endif<br>    &lt;/div&gt;<br>    <br>    &lt;form wire:submit.prevent=&quot;sendMessage&quot;&gt;<br>        &lt;input <br>            type=&quot;text&quot; <br>            wire:model=&quot;input&quot; <br>            placeholder=&quot;Type your message...&quot;<br>            class=&quot;message-input&quot;<br>        &gt;<br>        &lt;button type=&quot;submit&quot;&gt;Send&lt;/button&gt;<br>    &lt;/form&gt;<br>&lt;/div&gt;</pre><h3>Feature 3: Streaming Responses — Real-Time AI Experience</h3><p><strong>When to Use:</strong></p><ul><li>Long-form content generation</li><li>Interactive storytelling</li><li>Live document creation</li><li>Better user experience (no waiting)</li></ul><p><strong>Example: AI Story Generator with Streaming</strong></p><pre>namespace App\Http\Controllers;<br>use Illuminate\Http\Request;<br>use Laravel\Ai\Facades\Ai;<br>class StoryGeneratorController extends Controller<br>{<br>    public function generate(Request $request)<br>    {<br>        $topic = $request-&gt;input(&#39;topic&#39;, &#39;a mysterious adventure&#39;);<br>        <br>        return response()-&gt;stream(function () use ($topic) {<br>            Ai::systemPrompt(&#39;You are a creative storyteller.&#39;)<br>                -&gt;generate(&quot;Write an engaging short story about {$topic}&quot;)<br>                -&gt;stream(function ($chunk) {<br>                    echo &quot;data: &quot; . json_encode([<br>                        &#39;text&#39; =&gt; $chunk-&gt;text,<br>                        &#39;done&#39; =&gt; false<br>                    ]) . &quot;\n\n&quot;;<br>                    <br>                    ob_flush();<br>                    flush();<br>                });<br>            <br>            // Signal completion<br>            echo &quot;data: &quot; . json_encode([&#39;done&#39; =&gt; true]) . &quot;\n\n&quot;;<br>        }, 200, [<br>            &#39;Content-Type&#39; =&gt; &#39;text/event-stream&#39;,<br>            &#39;Cache-Control&#39; =&gt; &#39;no-cache&#39;,<br>            &#39;X-Accel-Buffering&#39; =&gt; &#39;no&#39;,<br>        ]);<br>    }<br>}</pre><p><strong>Frontend (JavaScript):</strong></p><pre>function generateStory(topic) {<br>    const output = document.getElementById(&#39;story-output&#39;);<br>    output.innerHTML = &#39;&#39;;<br>    <br>    const eventSource = new EventSource(`/ai/story/generate?topic=${encodeURIComponent(topic)}`);<br>    <br>    eventSource.onmessage = function(event) {<br>        const data = JSON.parse(event.data);<br>        <br>        if (data.done) {<br>            eventSource.close();<br>            console.log(&#39;Story generation complete!&#39;);<br>        } else {<br>            output.innerHTML += data.text;<br>            // Auto-scroll<br>            output.scrollTop = output.scrollHeight;<br>        }<br>    };<br>    <br>    eventSource.onerror = function() {<br>        eventSource.close();<br>        console.error(&#39;Connection error&#39;);<br>    };<br>}</pre><h3>Feature 4: Embeddings — Semantic Search &amp; Recommendations</h3><p><strong>When to Use:</strong></p><ul><li>Smart product search</li><li>Content recommendations</li><li>Similarity matching</li><li>Document clustering</li></ul><p><strong>Example: Intelligent Product Search System</strong></p><pre>namespace App\Services;<br>use Laravel\Ai\Facades\Ai;<br>use App\Models\Product;<br>use Illuminate\Support\Facades\DB;<br>class SmartProductSearch<br>{<br>    /**<br>     * Index a product by creating its embedding<br>     */<br>    public function indexProduct(Product $product)<br>    {<br>        $text = $this-&gt;prepareProductText($product);<br>        <br>        // Generate embedding<br>        $embedding = Ai::embeddings()-&gt;create($text);<br>        <br>        // Store embedding as JSON<br>        $product-&gt;update([<br>            &#39;embedding&#39; =&gt; json_encode($embedding-&gt;vector)<br>        ]);<br>    }<br>    <br>    /**<br>     * Search products using semantic similarity<br>     */<br>    public function search(string $query, int $limit = 10)<br>    {<br>        // Generate query embedding<br>        $queryEmbedding = Ai::embeddings()-&gt;create($query);<br>        <br>        // Find similar products using vector similarity<br>        // Note: Requires PostgreSQL with pgvector extension<br>        $products = DB::select(&quot;<br>            SELECT <br>                *,<br>                1 - (embedding &lt;=&gt; ?::vector) as similarity<br>            FROM products<br>            WHERE embedding IS NOT NULL<br>            ORDER BY embedding &lt;=&gt; ?::vector<br>            LIMIT ?<br>        &quot;, [<br>            json_encode($queryEmbedding-&gt;vector),<br>            json_encode($queryEmbedding-&gt;vector),<br>            $limit<br>        ]);<br>        <br>        return collect($products);<br>    }<br>    <br>    /**<br>     * Find similar products<br>     */<br>    public function findSimilar(Product $product, int $limit = 5)<br>    {<br>        if (!$product-&gt;embedding) {<br>            $this-&gt;indexProduct($product);<br>        }<br>        <br>        return DB::select(&quot;<br>            SELECT <br>                *,<br>                1 - (embedding &lt;=&gt; ?::vector) as similarity<br>            FROM products<br>            WHERE id != ? AND embedding IS NOT NULL<br>            ORDER BY embedding &lt;=&gt; ?::vector<br>            LIMIT ?<br>        &quot;, [<br>            $product-&gt;embedding,<br>            $product-&gt;id,<br>            $product-&gt;embedding,<br>            $limit<br>        ]);<br>    }<br>    <br>    private function prepareProductText(Product $product)<br>    {<br>        return implode(&#39; &#39;, [<br>            $product-&gt;name,<br>            $product-&gt;description,<br>            $product-&gt;category,<br>            implode(&#39; &#39;, $product-&gt;tags ?? [])<br>        ]);<br>    }<br>}<br>// Usage in Controller<br>class ProductController extends Controller<br>{<br>    protected $searchService;<br>    <br>    public function __construct(SmartProductSearch $searchService)<br>    {<br>        $this-&gt;searchService = $searchService;<br>    }<br>    <br>    public function search(Request $request)<br>    {<br>        // Natural language search<br>        $results = $this-&gt;searchService-&gt;search(<br>            $request-&gt;input(&#39;q&#39;)<br>        );<br>        <br>        return view(&#39;products.search&#39;, [<br>            &#39;products&#39; =&gt; $results,<br>            &#39;query&#39; =&gt; $request-&gt;input(&#39;q&#39;)<br>        ]);<br>    }<br>}</pre><p><strong>Migration for Vector Support:</strong></p><pre>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Support\Facades\DB;<br><br>class AddEmbeddingToProductsTable extends Migration<br>{<br>    public function up()<br>    {<br>        // Enable pgvector extension<br>        DB::statement(&#39;CREATE EXTENSION IF NOT EXISTS vector&#39;);<br>        <br>        Schema::table(&#39;products&#39;, function ($table) {<br>            // Add vector column (1536 dimensions for OpenAI embeddings)<br>            DB::statement(&#39;ALTER TABLE products ADD COLUMN embedding vector(1536)&#39;);<br>        });<br>        <br>        // Create index for faster similarity search<br>        DB::statement(&#39;CREATE INDEX products_embedding_idx ON products USING ivfflat (embedding vector_cosine_ops)&#39;);<br>    }<br>    <br>    public function down()<br>    {<br>        Schema::table(&#39;products&#39;, function ($table) {<br>            $table-&gt;dropColumn(&#39;embedding&#39;);<br>        });<br>    }<br>}</pre><h3>Feature 5: Image Generation — Visual Content Creation</h3><p><strong>When to Use:</strong></p><ul><li>Product mockups</li><li>Social media graphics</li><li>Marketing materials</li><li>Dynamic thumbnails</li></ul><p><strong>Example: AI-Powered Product Image Generator</strong></p><pre>namespace App\Services;<br>use Laravel\Ai\Facades\Ai;<br>use Illuminate\Support\Facades\Storage;<br>class ProductImageGenerator<br>{<br>    public function generateProductImage(array $data)<br>    {<br>        $prompt = $this-&gt;buildPrompt($data);<br>        <br>        // Generate image<br>        $image = Ai::images()-&gt;create(<br>            prompt: $prompt,<br>            size: &#39;1024x1024&#39;,<br>            quality: &#39;high&#39;,<br>            style: &#39;natural&#39;<br>        );<br>        <br>        // Download and save<br>        $filename = &#39;products/&#39; . uniqid() . &#39;.png&#39;;<br>        $imageContent = file_get_contents($image-&gt;url);<br>        Storage::put($filename, $imageContent);<br>        <br>        return [<br>            &#39;url&#39; =&gt; Storage::url(https://medium.com/$filename),<br>            &#39;path&#39; =&gt; $filename<br>        ];<br>    }<br>    <br>    public function generateVariations(string $imagePath, int $count = 3)<br>    {<br>        $variations = Ai::images()-&gt;variations(<br>            image: Storage::path($imagePath),<br>            n: $count,<br>            size: &#39;1024x1024&#39;<br>        );<br>        <br>        $savedVariations = [];<br>        foreach ($variations as $variation) {<br>            $filename = &#39;products/variations/&#39; . uniqid() . &#39;.png&#39;;<br>            Storage::put($filename, file_get_contents($variation-&gt;url));<br>            $savedVariations[] = Storage::url(https://medium.com/$filename);<br>        }<br>        <br>        return $savedVariations;<br>    }<br>    <br>    private function buildPrompt(array $data)<br>    {<br>        return &quot;Professional product photography of {$data[&#39;name&#39;]}, &quot;<br>            . &quot;{$data[&#39;description&#39;]}, &quot;<br>            . &quot;studio lighting, white background, &quot;<br>            . &quot;high resolution, commercial quality&quot;;<br>    }<br>}<br>// Usage<br>$generator = new ProductImageGenerator();<br>$image = $generator-&gt;generateProductImage([<br>    &#39;name&#39; =&gt; &#39;Premium Leather Wallet&#39;,<br>    &#39;description&#39; =&gt; &#39;sleek brown leather wallet with gold accents&#39;<br>]);</pre><h3>Feature 6: Audio Processing — Voice Capabilities</h3><p><strong>When to Use:</strong></p><ul><li>Voice notes transcription</li><li>Podcast transcription</li><li>Text-to-speech for accessibility</li><li>Voice commands</li></ul><p><strong>Example: Voice Note System</strong></p><pre>namespace App\Http\Controllers;<br>use Illuminate\Http\Request;<br>use Laravel\Ai\Facades\Ai;<br>use App\Models\VoiceNote;<br>class VoiceNoteController extends Controller<br>{<br>    /**<br>     * Transcribe uploaded audio to text<br>     */<br>    public function transcribe(Request $request)<br>    {<br>        $request-&gt;validate([<br>            &#39;audio&#39; =&gt; &#39;required|file|mimes:mp3,wav,m4a|max:25000&#39;<br>        ]);<br>        <br>        $audioFile = $request-&gt;file(&#39;audio&#39;);<br>        <br>        // Transcribe audio<br>        $transcription = Ai::audio()-&gt;transcribe(<br>            file: $audioFile-&gt;getRealPath(),<br>            language: &#39;en&#39;, // or &#39;bn&#39; for Bangla<br>            prompt: &#39;This is a voice note about...&#39; // Optional context<br>        );<br>        <br>        // Save to database<br>        $voiceNote = VoiceNote::create([<br>            &#39;user_id&#39; =&gt; auth()-&gt;id(),<br>            &#39;title&#39; =&gt; $this-&gt;generateTitle($transcription-&gt;text),<br>            &#39;transcription&#39; =&gt; $transcription-&gt;text,<br>            &#39;audio_path&#39; =&gt; $audioFile-&gt;store(&#39;voice-notes&#39;),<br>            &#39;duration&#39; =&gt; $this-&gt;getAudioDuration($audioFile)<br>        ]);<br>        <br>        return response()-&gt;json([<br>            &#39;id&#39; =&gt; $voiceNote-&gt;id,<br>            &#39;transcription&#39; =&gt; $transcription-&gt;text<br>        ]);<br>    }<br>    <br>    /**<br>     * Convert text to speech<br>     */<br>    public function textToSpeech(Request $request)<br>    {<br>        $text = $request-&gt;input(&#39;text&#39;);<br>        <br>        $audio = Ai::audio()-&gt;speech(<br>            text: $text,<br>            voice: &#39;alloy&#39;, // Options: alloy, echo, fable, onyx, nova, shimmer<br>            speed: 1.0,<br>            model: &#39;tts-1-hd&#39; // High quality<br>        );<br>        <br>        // Save audio file<br>        $filename = &#39;tts/&#39; . uniqid() . &#39;.mp3&#39;;<br>        Storage::put($filename, $audio-&gt;content);<br>        <br>        return response()-&gt;json([<br>            &#39;audio_url&#39; =&gt; Storage::url(https://medium.com/$filename)<br>        ]);<br>    }<br>    <br>    /**<br>     * Auto-generate title from transcription<br>     */<br>    private function generateTitle(string $transcription)<br>    {<br>        $response = Ai::generate(<br>            &quot;Generate a short, descriptive title (max 50 chars) for this transcription: &quot; <br>            . substr($transcription, 0, 200)<br>        );<br>        <br>        return substr($response-&gt;text, 0, 50);<br>    }<br>    <br>    private function getAudioDuration($file)<br>    {<br>        // Use getID3 or similar library<br>        return 0;<br>    }<br>}</pre><p><strong>Bangla Voice Note Example:</strong></p><pre>public function transcribeBangla(Request $request)<br>{<br>    $audioFile = $request-&gt;file(&#39;audio&#39;);<br>    <br>    // Transcribe Bangla audio<br>    $transcription = Ai::audio()-&gt;transcribe(<br>        file: $audioFile-&gt;getRealPath(),<br>        language: &#39;bn&#39;, // Bangla<br>        prompt: &#39;এটি একটি বাংলা ভয়েস নোট&#39; // Helps with accuracy<br>    );<br>    <br>    // Save the Bangla transcription<br>    auth()-&gt;user()-&gt;notes()-&gt;create([<br>        &#39;content&#39; =&gt; $transcription-&gt;text,<br>        &#39;language&#39; =&gt; &#39;bn&#39;,<br>        &#39;audio_path&#39; =&gt; $audioFile-&gt;store(&#39;voice-notes&#39;)<br>    ]);<br>    <br>    return response()-&gt;json([<br>        &#39;text&#39; =&gt; $transcription-&gt;text<br>    ]);<br>}</pre><h3>Feature 7: Function Calling — AI That Takes Actions</h3><p><strong>When to Use:</strong></p><ul><li>Database queries</li><li>API integrations</li><li>Complex workflows</li><li>Multi-step processes</li></ul><p><strong>Example: AI Order Assistant with Function Calling</strong></p><pre>namespace App\Services;<br>use Laravel\Ai\Facades\Ai;<br>use App\Models\Order;<br>use App\Models\Product;<br>class OrderAssistantService<br>{<br>    protected $tools = [<br>        [<br>            &#39;type&#39; =&gt; &#39;function&#39;,<br>            &#39;function&#39; =&gt; [<br>                &#39;name&#39; =&gt; &#39;check_order_status&#39;,<br>                &#39;description&#39; =&gt; &#39;Check the status of a customer order&#39;,<br>                &#39;parameters&#39; =&gt; [<br>                    &#39;type&#39; =&gt; &#39;object&#39;,<br>                    &#39;properties&#39; =&gt; [<br>                        &#39;order_number&#39; =&gt; [<br>                            &#39;type&#39; =&gt; &#39;string&#39;,<br>                            &#39;description&#39; =&gt; &#39;The order number (e.g., ORD-12345)&#39;<br>                        ]<br>                    ],<br>                    &#39;required&#39; =&gt; [&#39;order_number&#39;]<br>                ]<br>            ]<br>        ],<br>        [<br>            &#39;type&#39; =&gt; &#39;function&#39;,<br>            &#39;function&#39; =&gt; [<br>                &#39;name&#39; =&gt; &#39;search_products&#39;,<br>                &#39;description&#39; =&gt; &#39;Search for products in the catalog&#39;,<br>                &#39;parameters&#39; =&gt; [<br>                    &#39;type&#39; =&gt; &#39;object&#39;,<br>                    &#39;properties&#39; =&gt; [<br>                        &#39;query&#39; =&gt; [<br>                            &#39;type&#39; =&gt; &#39;string&#39;,<br>                            &#39;description&#39; =&gt; &#39;Search query&#39;<br>                        ],<br>                        &#39;category&#39; =&gt; [<br>                            &#39;type&#39; =&gt; &#39;string&#39;,<br>                            &#39;description&#39; =&gt; &#39;Product category filter&#39;<br>                        ]<br>                    ],<br>                    &#39;required&#39; =&gt; [&#39;query&#39;]<br>                ]<br>            ]<br>        ],<br>        [<br>            &#39;type&#39; =&gt; &#39;function&#39;,<br>            &#39;function&#39; =&gt; [<br>                &#39;name&#39; =&gt; &#39;calculate_shipping&#39;,<br>                &#39;description&#39; =&gt; &#39;Calculate shipping cost&#39;,<br>                &#39;parameters&#39; =&gt; [<br>                    &#39;type&#39; =&gt; &#39;object&#39;,<br>                    &#39;properties&#39; =&gt; [<br>                        &#39;zip_code&#39; =&gt; [&#39;type&#39; =&gt; &#39;string&#39;],<br>                        &#39;weight&#39; =&gt; [&#39;type&#39; =&gt; &#39;number&#39;]<br>                    ],<br>                    &#39;required&#39; =&gt; [&#39;zip_code&#39;, &#39;weight&#39;]<br>                ]<br>            ]<br>        ]<br>    ];<br>    <br>    public function handleQuery(string $userQuery, int $userId)<br>    {<br>        $response = Ai::systemPrompt(<br>            &#39;You are a helpful e-commerce assistant. Use the available functions to help customers.&#39;<br>        )<br>        -&gt;tools($this-&gt;tools)<br>        -&gt;generate($userQuery);<br>        <br>        // Check if AI wants to call a function<br>        if ($response-&gt;hasToolCalls()) {<br>            return $this-&gt;executeToolCalls($response-&gt;toolCalls(), $userId);<br>        }<br>        <br>        return $response-&gt;text;<br>    }<br>    <br>    protected function executeToolCalls($toolCalls, $userId)<br>    {<br>        $results = [];<br>        <br>        foreach ($toolCalls as $call) {<br>            $result = match($call-&gt;name) {<br>                &#39;check_order_status&#39; =&gt; $this-&gt;checkOrderStatus(<br>                    $call-&gt;arguments[&#39;order_number&#39;], <br>                    $userId<br>                ),<br>                &#39;search_products&#39; =&gt; $this-&gt;searchProducts(<br>                    $call-&gt;arguments[&#39;query&#39;],<br>                    $call-&gt;arguments[&#39;category&#39;] ?? null<br>                ),<br>                &#39;calculate_shipping&#39; =&gt; $this-&gt;calculateShipping(<br>                    $call-&gt;arguments[&#39;zip_code&#39;],<br>                    $call-&gt;arguments[&#39;weight&#39;]<br>                ),<br>                default =&gt; &#39;Function not found&#39;<br>            };<br>            <br>            $results[] = $result;<br>        }<br>        <br>        // Send results back to AI for natural language response<br>        $finalResponse = Ai::systemPrompt(<br>            &#39;You are a helpful e-commerce assistant. Format the function results into a friendly response.&#39;<br>        )<br>        -&gt;generate(<br>            &quot;User asked: {$userQuery}\n\nFunction results:\n&quot; . implode(&quot;\n&quot;, $results)<br>        );<br>        <br>        return $finalResponse-&gt;text;<br>    }<br>    <br>    protected function checkOrderStatus(string $orderNumber, int $userId)<br>    {<br>        $order = Order::where(&#39;order_number&#39;, $orderNumber)<br>                     -&gt;where(&#39;user_id&#39;, $userId)<br>                     -&gt;first();<br>        <br>        if (!$order) {<br>            return &quot;Order {$orderNumber} not found for this user.&quot;;<br>        }<br>        <br>        return &quot;Order {$orderNumber} status: {$order-&gt;status}. &quot;<br>             . &quot;Estimated delivery: {$order-&gt;estimated_delivery-&gt;format(&#39;M d, Y&#39;)}. &quot;<br>             . &quot;Tracking: {$order-&gt;tracking_number}&quot;;<br>    }<br>    <br>    protected function searchProducts(string $query, ?string $category = null)<br>    {<br>        $products = Product::where(&#39;name&#39;, &#39;LIKE&#39;, &quot;%{$query}%&quot;);<br>        <br>        if ($category) {<br>            $products-&gt;where(&#39;category&#39;, $category);<br>        }<br>        <br>        $results = $products-&gt;limit(5)-&gt;get();<br>        <br>        return &quot;Found {$results-&gt;count()} products: &quot; <br>             . $results-&gt;pluck(&#39;name&#39;)-&gt;implode(&#39;, &#39;);<br>    }<br>    <br>    protected function calculateShipping(string $zipCode, float $weight)<br>    {<br>        // Simple calculation logic<br>        $baseRate = 5.99;<br>        $weightRate = $weight * 0.5;<br>        $total = $baseRate + $weightRate;<br>        <br>        return &quot;Shipping to {$zipCode}: \${$total} (Base: \${$baseRate} + Weight: \${$weightRate})&quot;;<br>    }<br>}<br>// Usage in Controller<br>class ChatController extends Controller<br>{<br>    public function sendMessage(Request $request, OrderAssistantService $assistant)<br>    {<br>        $response = $assistant-&gt;handleQuery(<br>            $request-&gt;input(&#39;message&#39;),<br>            auth()-&gt;id()<br>        );<br>        <br>        return response()-&gt;json([&#39;reply&#39; =&gt; $response]);<br>    }<br>}</pre><p><strong>Example Conversation:</strong></p><pre>User: &quot;Where is my order ORD-12345?&quot;<br>AI: → Calls check_order_status(&#39;ORD-12345&#39;)<br>AI: &quot;Your order ORD-12345 is currently in transit and should arrive by March 15, 2026. Tracking number: 1Z999AA10123456784.&quot;</pre><pre>User: &quot;Find me wireless headphones under $100&quot;<br>AI: → Calls search_products(&#39;wireless headphones&#39;)<br>AI: &quot;I found 5 wireless headphones: Sony WH-1000XM4, Bose QuietComfort, JBL Tune 510BT...&quot;</pre><h3>Feature 8: Web Search Integration — Current Information</h3><p><strong>When to Use:</strong></p><ul><li>Real-time data needs</li><li>Current events</li><li>Price checking</li><li>News updates</li></ul><p><strong>Example: Smart Research Assistant</strong></p><pre>namespace App\Services;<br>use Laravel\Ai\Facades\Ai;<br>class ResearchAssistant<br>{<br>    public function research(string $topic)<br>    {<br>        $response = Ai::tools([<br>            [&#39;type&#39; =&gt; &#39;web_search&#39;]<br>        ])<br>        -&gt;systemPrompt(&#39;You are a research assistant. Provide accurate, well-sourced information.&#39;)<br>        -&gt;generate(&quot;Research and provide detailed information about: {$topic}&quot;);<br>        <br>        return $response-&gt;text;<br>    }<br>    <br>    public function compareProducts(string $product1, string $product2)<br>    {<br>        $response = Ai::tools([<br>            [&#39;type&#39; =&gt; &#39;web_search&#39;]<br>        ])<br>        -&gt;generate(&quot;Compare {$product1} vs {$product2}. Include current prices, specs, and reviews.&quot;);<br>        <br>        return $response-&gt;text;<br>    }<br>    <br>    public function getCurrentNews(string $category)<br>    {<br>        $response = Ai::tools([<br>            [&#39;type&#39; =&gt; &#39;web_search&#39;]<br>        ])<br>        -&gt;generate(&quot;What are the latest news in {$category} today?&quot;);<br>        <br>        return $response-&gt;text;<br>    }<br>}</pre><h3>Complete Real-World Project: AI-Powered E-Commerce Platform</h3><p>Let’s combine everything into a comprehensive example:</p><pre>namespace App\Services;<br>use Laravel\Ai\Facades\Ai;<br>use App\Models\Product;<br>use App\Models\Order;<br>use App\Models\Review;<br>class EcommerceAiEngine<br>{<br>    /**<br>     * 1. Smart Product Recommendations<br>     */<br>    public function recommendProducts(string $userPreference, int $userId)<br>    {<br>        // Get embedding for user preference<br>        $preferenceEmbedding = Ai::embeddings()-&gt;create($userPreference);<br>        <br>        // Find similar products<br>        $products = Product::selectRaw(<br>            &#39;*, 1 - (embedding &lt;=&gt; ?::vector) as similarity&#39;,<br>            [json_encode($preferenceEmbedding-&gt;vector)]<br>        )<br>        -&gt;orderByDesc(&#39;similarity&#39;)<br>        -&gt;limit(10)<br>        -&gt;get();<br>        <br>        // Use AI to explain recommendations<br>        $productList = $products-&gt;map(fn($p) =&gt; <br>            &quot;{$p-&gt;name} - \${$p-&gt;price} - Rating: {$p-&gt;rating}/5&quot;<br>        )-&gt;implode(&quot;\n&quot;);<br>        <br>        $explanation = Ai::generate(<br>            &quot;User is looking for: {$userPreference}\n\n&quot;<br>            . &quot;Available products:\n{$productList}\n\n&quot;<br>            . &quot;Recommend the top 3 and explain why they match the preference.&quot;<br>        );<br>        <br>        return [<br>            &#39;products&#39; =&gt; $products-&gt;take(3),<br>            &#39;explanation&#39; =&gt; $explanation-&gt;text<br>        ];<br>    }<br>    <br>    /**<br>     * 2. Automated Product Description Generation<br>     */<br>    public function generateProductContent(Product $product)<br>    {<br>        $description = Ai::systemPrompt(<br>            &#39;You are an expert e-commerce copywriter. Write compelling, SEO-friendly product descriptions.&#39;<br>        )<br>        -&gt;temperature(0.8)<br>        -&gt;generate(<br>            &quot;Write a product description for:\n&quot;<br>            . &quot;Name: {$product-&gt;name}\n&quot;<br>            . &quot;Category: {$product-&gt;category}\n&quot;<br>            . &quot;Price: \${$product-&gt;price}\n&quot;<br>            . &quot;Features: &quot; . implode(&#39;, &#39;, $product-&gt;features)<br>        );<br>        <br>        // Generate product image<br>        $image = Ai::images()-&gt;create(<br>            prompt: &quot;Professional product photo of {$product-&gt;name}, studio lighting, white background&quot;,<br>            size: &#39;1024x1024&#39;<br>        );<br>        <br>        return [<br>            &#39;description&#39; =&gt; $description-&gt;text,<br>            &#39;image_url&#39; =&gt; $image-&gt;url<br>        ];<br>    }<br>    <br>    /**<br>     * 3. Review Sentiment Analysis &amp; Summary<br>     */<br>    public function analyzeReviews(Product $product)<br>    {<br>        $reviews = Review::where(&#39;product_id&#39;, $product-&gt;id)<br>            -&gt;latest()<br>            -&gt;limit(50)<br>            -&gt;get();<br>        <br>        $reviewText = $reviews-&gt;map(fn($r) =&gt; <br>            &quot;Rating: {$r-&gt;rating}/5 - {$r-&gt;comment}&quot;<br>        )-&gt;implode(&quot;\n&quot;);<br>        <br>        $analysis = Ai::generate(<br>            &quot;Analyze these product reviews and provide:\n&quot;<br>            . &quot;1. Overall sentiment\n&quot;<br>            . &quot;2. Common praise points\n&quot;<br>            . &quot;3. Common complaints\n&quot;<br>            . &quot;4. Summary\n\n&quot;<br>            . &quot;Reviews:\n{$reviewText}&quot;<br>        );<br>        <br>        return $analysis-&gt;text;<br>    }<br>    <br>    /**<br>     * 4. Customer Support Chatbot<br>     */<br>    public function handleCustomerQuery(string $query, int $userId, array $context = [])<br>    {<br>        $tools = [<br>            [<br>                &#39;type&#39; =&gt; &#39;function&#39;,<br>                &#39;function&#39; =&gt; [<br>                    &#39;name&#39; =&gt; &#39;get_order_info&#39;,<br>                    &#39;description&#39; =&gt; &#39;Get order information&#39;,<br>                    &#39;parameters&#39; =&gt; [<br>                        &#39;type&#39; =&gt; &#39;object&#39;,<br>                        &#39;properties&#39; =&gt; [<br>                            &#39;order_number&#39; =&gt; [&#39;type&#39; =&gt; &#39;string&#39;]<br>                        ]<br>                    ]<br>                ]<br>            ],<br>            [<br>                &#39;type&#39; =&gt; &#39;function&#39;,<br>                &#39;function&#39; =&gt; [<br>                    &#39;name&#39; =&gt; &#39;search_products&#39;,<br>                    &#39;description&#39; =&gt; &#39;Search for products&#39;,<br>                    &#39;parameters&#39; =&gt; [<br>                        &#39;type&#39; =&gt; &#39;object&#39;,<br>                        &#39;properties&#39; =&gt; [<br>                            &#39;query&#39; =&gt; [&#39;type&#39; =&gt; &#39;string&#39;]<br>                        ]<br>                    ]<br>                ]<br>            ],<br>            [&#39;type&#39; =&gt; &#39;web_search&#39;]<br>        ];<br>        <br>        $response = Ai::systemPrompt(<br>            &#39;You are a friendly e-commerce support agent. Help customers with orders, products, and general questions.&#39;<br>        )<br>        -&gt;tools($tools)<br>        -&gt;chat($context)<br>        -&gt;generate($query);<br>        <br>        return $this-&gt;processResponse($response, $userId);<br>    }<br>    <br>    /**<br>     * 5. Smart Search with Natural Language<br>     */<br>    public function naturalLanguageSearch(string $query)<br>    {<br>        // Convert natural language to structured search<br>        $searchParams = Ai::generate(<br>            &quot;Convert this natural language query into structured search parameters (return JSON):\n&quot;<br>            . &quot;Query: {$query}\n\n&quot;<br>            . &quot;Return format: {\&quot;keywords\&quot;: [], \&quot;category\&quot;: \&quot;\&quot;, \&quot;priceRange\&quot;: {\&quot;min\&quot;: 0, \&quot;max\&quot;: 0}, \&quot;features\&quot;: []}&quot;<br>        );<br>        <br>        $params = json_decode($searchParams-&gt;text, true);<br>        <br>        // Execute search<br>        $products = Product::query();<br>        <br>        if (!empty($params[&#39;keywords&#39;])) {<br>            foreach ($params[&#39;keywords&#39;] as $keyword) {<br>                $products-&gt;where(&#39;name&#39;, &#39;LIKE&#39;, &quot;%{$keyword}%&quot;);<br>            }<br>        }<br>        <br>        if (!empty($params[&#39;category&#39;])) {<br>            $products-&gt;where(&#39;category&#39;, $params[&#39;category&#39;]);<br>        }<br>        <br>        if (!empty($params[&#39;priceRange&#39;])) {<br>            $products-&gt;whereBetween(&#39;price&#39;, [<br>                $params[&#39;priceRange&#39;][&#39;min&#39;],<br>                $params[&#39;priceRange&#39;][&#39;max&#39;]<br>            ]);<br>        }<br>        <br>        return $products-&gt;get();<br>    }<br>    <br>    /**<br>     * 6. Dynamic Email Generation<br>     */<br>    public function generateOrderEmail(Order $order, string $type)<br>    {<br>        $email = Ai::systemPrompt(<br>            &#39;You are a professional email writer for an e-commerce company.&#39;<br>        )<br>        -&gt;generate(<br>            &quot;Write a {$type} email for:\n&quot;<br>            . &quot;Order: {$order-&gt;order_number}\n&quot;<br>            . &quot;Customer: {$order-&gt;customer_name}\n&quot;<br>            . &quot;Items: {$order-&gt;items-&gt;pluck(&#39;name&#39;)-&gt;implode(&#39;, &#39;)}\n&quot;<br>            . &quot;Total: \${$order-&gt;total}\n&quot;<br>            . &quot;Status: {$order-&gt;status}&quot;<br>        );<br>        <br>        return $email-&gt;text;<br>    }<br>    <br>    protected function processResponse($response, $userId)<br>    {<br>        if ($response-&gt;hasToolCalls()) {<br>            // Execute function calls<br>            // Return formatted response<br>        }<br>        <br>        return $response-&gt;text;<br>    }<br>}</pre><p><strong>Usage in Controller:</strong></p><pre>namespace App\Http\Controllers;<br>use App\Services\EcommerceAiEngine;<br>use Illuminate\Http\Request;<br>class AiShoppingController extends Controller<br>{<br>    protected $aiEngine;<br>    <br>    public function __construct(EcommerceAiEngine $aiEngine)<br>    {<br>        $this-&gt;aiEngine = $aiEngine;<br>    }<br>    <br>    public function recommend(Request $request)<br>    {<br>        $recommendations = $this-&gt;aiEngine-&gt;recommendProducts(<br>            $request-&gt;input(&#39;preference&#39;),<br>            auth()-&gt;id()<br>        );<br>        <br>        return view(&#39;shop.recommendations&#39;, $recommendations);<br>    }<br>    <br>    public function search(Request $request)<br>    {<br>        $products = $this-&gt;aiEngine-&gt;naturalLanguageSearch(<br>            $request-&gt;input(&#39;q&#39;)<br>        );<br>        <br>        return view(&#39;shop.search&#39;, compact(&#39;products&#39;));<br>    }<br>}</pre><h3>Best Practices &amp; Pro Tips</h3><h3>1. Cost Management</h3><pre>// Cache AI responses<br>use Illuminate\Support\Facades\Cache;<br>public function getCachedResponse(string $prompt, int $ttl = 3600)<br>{<br>    $key = &#39;ai_response_&#39; . md5($prompt);<br>    <br>    return Cache::remember($key, $ttl, function () use ($prompt) {<br>        return Ai::generate($prompt)-&gt;text;<br>    });<br>}</pre><h3>2. Error Handling</h3><pre>use Laravel\Ai\Exceptions\AiException;<br>try {<br>    $response = Ai::generate($prompt);<br>} catch (AiException $e) {<br>    Log::error(&#39;AI Error: &#39; . $e-&gt;getMessage());<br>    <br>    // Fallback to different provider<br>    $response = Ai::driver(&#39;openai&#39;)-&gt;generate($prompt);<br>}</pre><h3>3. Rate Limiting</h3><pre>use Illuminate\Support\Facades\RateLimiter;<br><br>public function generateContent(Request $request)<br>{<br>    $key = &#39;ai_generate_&#39; . $request-&gt;user()-&gt;id;<br>    <br>    if (RateLimiter::tooManyAttempts($key, 10)) {<br>        return response()-&gt;json([<br>            &#39;error&#39; =&gt; &#39;Too many requests. Please wait.&#39;<br>        ], 429);<br>    }<br>    <br>    RateLimiter::hit($key, 60); // 10 requests per minute<br>    <br>    $response = Ai::generate($request-&gt;input(&#39;prompt&#39;));<br>    <br>    return response()-&gt;json([&#39;result&#39; =&gt; $response-&gt;text]);<br>}</pre><h3>4. Queue Long-Running Tasks</h3><pre>namespace App\Jobs;<br>use Laravel\Ai\Facades\Ai;<br>class GenerateProductDescriptions implements ShouldQueue<br>{<br>    public function handle()<br>    {<br>        Product::whereNull(&#39;ai_description&#39;)<br>            -&gt;chunk(10, function ($products) {<br>                foreach ($products as $product) {<br>                    $description = Ai::generate(<br>                        &quot;Write a product description for: {$product-&gt;name}&quot;<br>                    );<br>                    <br>                    $product-&gt;update([<br>                        &#39;ai_description&#39; =&gt; $description-&gt;text<br>                    ]);<br>                }<br>            });<br>    }<br>}</pre><h3>5. Testing AI Features</h3><pre>use Laravel\Ai\Facades\Ai;<br>use Laravel\Ai\Testing\FakeResponse;<br><br>public function test_generates_product_description()<br>{<br>    Ai::fake([<br>        new FakeResponse(&#39;This is a great product!&#39;)<br>    ]);<br>    <br>    $service = new ProductService();<br>    $description = $service-&gt;generateDescription($productData);<br>    <br>    $this-&gt;assertEquals(&#39;This is a great product!&#39;, $description);<br>    <br>    Ai::assertGenerated(function ($prompt) {<br>        return str_contains($prompt, &#39;product description&#39;);<br>    });<br>}</pre><h3>When NOT to Use Laravel AI SDK</h3><ol><li><strong>Simple text processing</strong> — Use regex or string functions</li><li><strong>Static content</strong> — Store in database</li><li><strong>Real-time requirements</strong> — AI responses have latency</li><li><strong>Limited budget</strong> — API calls cost money</li><li><strong>Highly regulated content</strong> — May need human oversight</li></ol><h3>Performance Optimization Tips</h3><h3>1. Batch Processing</h3><pre>// Instead of individual requests<br>foreach ($products as $product) {<br>    $description = Ai::generate(&quot;Describe: {$product-&gt;name}&quot;);<br>}<br><br>// Batch them<br>$prompt = &quot;Generate descriptions for:\n&quot;;<br>foreach ($products as $product) {<br>    $prompt .= &quot;- {$product-&gt;name}\n&quot;;<br>}<br>$descriptions = Ai::generate($prompt);</pre><h3>2. Use Appropriate Models</h3><pre>// Fast, cheap for simple tasks<br>$response = Ai::using(&#39;claude-haiku-4-5-20251001&#39;)-&gt;generate($prompt);<br><br>// Smart, balanced<br>$response = Ai::using(&#39;claude-sonnet-4-5-20250929&#39;)-&gt;generate($prompt);<br>// Most capable for complex tasks<br>$response = Ai::using(&#39;claude-opus-4-5-20251101&#39;)-&gt;generate($prompt);</pre><h3>3. Implement Smart Caching</h3><pre>class AiCacheService<br>{<br>    public function generate(string $prompt, int $ttl = 86400)<br>    {<br>        $cacheKey = &#39;ai_&#39; . hash(&#39;sha256&#39;, $prompt);<br>        <br>        return Cache::remember($cacheKey, $ttl, function () use ($prompt) {<br>            return Ai::generate($prompt)-&gt;text;<br>        });<br>    }<br>}</pre><h3>Conclusion: The Future is Here</h3><p>Laravel AI SDK represents a major shift in how we build web applications. It’s not just about adding AI features — it’s about reimagining what’s possible with Laravel.</p><h3>What Covered:</h3><p>✅ Multi-provider support with seamless switching ✅ Text generation for content creation ✅ Chat conversations for intelligent assistants ✅ Streaming for real-time experiences ✅ Embeddings for semantic search ✅ Image generation for visual content ✅ Audio processing for voice features ✅ Function calling for complex workflows ✅ Web search for current information</p><h3>Getting Started Today:</h3><pre>composer require laravel/ai<br>php artisan vendor:publish --provider=&quot;Laravel\Ai\AiServiceProvider&quot;<br>php artisan migrate</pre><p>The Laravel ecosystem just got a whole lot smarter. Start building!</p><h3>Resources</h3><ul><li><strong>Official Documentation</strong>: <a href="https://laravel.com/docs/12.x/ai-sdk">https://laravel.com/docs/12.x/ai-sdk</a></li></ul><p><em>What AI-powered features will you build with Laravel AI SDK? Share your ideas in the comments!</em></p><p><strong>Tags:</strong> #Laravel #AI #PHP #WebDevelopment #MachineLearning #ArtificialIntelligence #OpenAI #Anthropic #Claude #Programming</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c5fc86a1be4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Go’s Runtime: A Deep Dive into Goroutines, Scheduling, and Concurrency]]></title>
            <link>https://medium.com/@tanvirhossenbappy751/understanding-gos-runtime-a-deep-dive-into-goroutines-scheduling-and-concurrency-5e63b4399793?source=rss-d8f8c06b0a32------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e63b4399793</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Tanvir Hossen Bappy]]></dc:creator>
            <pubDate>Sat, 31 Jan 2026 17:19:27 GMT</pubDate>
            <atom:updated>2026-01-31T17:19:27.488Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How Go manages to run millions of goroutines efficiently on just a handful of OS threads</em></p><p>I’ve been learning Go recently, and honestly, the more I dig into how it handles concurrency, the more impressed I get. When you first hear “millions of goroutines on a few OS threads,” it sounds almost too good to be true. But once you understand what’s happening under the hood, it all makes sense.</p><p>Let me share what I’ve learned about Go’s runtime, breaking down the concepts that initially seemed confusing but are actually quite elegant.</p><h3>The Problem Go Solved</h3><p>Think about traditional threaded programming for a second. Every time you spawn a thread, you’re asking the operating system to allocate around 1–2MB of stack space. Want to handle 10,000 concurrent connections? That’s potentially 10–20GB just for stacks. Not to mention the context switching overhead when the OS scheduler jumps between threads.</p><p>Go took a different approach. What if we could have lightweight execution units that don’t map 1:1 to OS threads? What if we could multiplex thousands of these lightweight units onto just a few OS threads?</p><p>That’s exactly what goroutines are.</p><h3>The M:P:G Model — Go’s Secret Sauce</h3><p>At the heart of Go’s runtime is something called the M:P:G model. When I first saw these letters, I was like “great, more acronyms.” But stick with me — this is actually brilliant.</p><p><strong>M (Machine):</strong> These are actual OS threads. Heavy, expensive, limited in number.</p><p><strong>G (Goroutine):</strong> These are Go’s lightweight threads. They start with just 2KB of stack (which can grow), and you can spawn millions of them.</p><p><strong>P (Processor):</strong> This is the interesting one. Think of P as a resource context or a scheduling context. By default, you get one P per CPU core.</p><p>Here’s the key insight: an M needs to be attached to a P to run goroutines. The P holds a local queue of runnable goroutines. So the relationship looks like this:</p><pre>M1 ←→ P1 ← [G1, G2, G3, G4]<br>M2 ←→ P2 ← [G5, G6, G7, G8]</pre><p>You might wonder: why not just M and G? Why add P in the middle?</p><p>The answer lies in efficiency. When Go needs to schedule goroutines, having P as an intermediary means:</p><ul><li>Each P has its own local queue (less lock contention)</li><li>When a goroutine blocks on a system call, the M can block, but the P can detach and find another M to keep running other goroutines</li><li>Work stealing between Ps is easier than between Ms</li></ul><h3>How the Go Scheduler Actually Works</h3><p>The scheduler in Go is cooperative with a twist. In older versions, goroutines would only yield control at specific points — function calls, channel operations, etc. This led to problems with tight loops that never yielded.</p><p>Go 1.14 introduced asynchronous preemption. Now there’s a background thread called sysmon that monitors running goroutines. If one has been running for more than 10ms, it sends a signal to preempt it. This was a game-changer for fairness.</p><h3>The Scheduling Strategy</h3><p>When a P needs to find work, it follows this priority:</p><ol><li>Check its own local queue (fastest, no locks needed)</li><li>Check the global queue (less common, needs a mutex)</li><li>Check the network poller for ready I/O</li><li>Try to steal work from another P’s queue</li></ol><p>That last one — work stealing — is particularly clever. If P1 is idle and P2 has a bunch of goroutines waiting, P1 will steal half of P2’s queue. This naturally balances the load across all your CPU cores.</p><h3>The Network Poller: Why Go’s I/O Doesn’t Block</h3><p>Here’s something that blew my mind when I first understood it. When you do network I/O in Go:</p><pre>conn.Read(buffer)</pre><p>You’d think this would block the entire OS thread, right? Nope.</p><p>Go uses something called a network poller built on top of epoll (on Linux), kqueue (on macOS), or IOCP (on Windows). Here’s what actually happens:</p><ol><li>Your goroutine calls conn.Read()</li><li>If data isn’t ready, the runtime registers this socket with the network poller</li><li>Your goroutine gets “parked” — removed from the run queue but not blocking the thread</li><li>The M continues running other goroutines</li><li>When data arrives, the network poller wakes your goroutine back up</li></ol><p>This is why Go can handle tens of thousands of concurrent connections without spawning tens of thousands of threads. The goroutines are parked in user space, waiting efficiently for I/O events.</p><h3>Epoll Under the Hood</h3><p>For those curious about the nitty-gritty, Go uses three main epoll operations:</p><p><strong>epoll_create():</strong> Sets up an epoll instance when the runtime starts</p><p><strong>epoll_ctl():</strong> Adds, modifies, or removes file descriptors to monitor</p><p><strong>epoll_wait():</strong> Blocks until one or more registered file descriptors are ready</p><p>The beauty is that epoll_wait can monitor thousands of sockets with a single system call. No need for one thread per connection.</p><h3>Memory Management and Stack Growth</h3><p>Another neat trick: goroutines start with a tiny 2KB stack. “But what if I need more?” I hear you ask.</p><p>Go’s runtime checks for stack overflow. When detected, it:</p><ol><li>Allocates a new, larger stack (typically doubles the size)</li><li>Copies all the data over</li><li>Updates all the pointers</li><li>Continues execution</li></ol><p>This is why goroutines can start small but grow as needed, up to 1GB if necessary. Compare this to OS threads with their fixed 1–2MB stacks.</p><h3>Real-World Example: HTTP Server</h3><p>Let’s look at what happens when you run a simple Go HTTP server:</p><pre>func handler(w http.ResponseWriter, r *http.Request) {<br>    fmt.Fprintln(w, &quot;Hello World&quot;)<br>}</pre><pre>func main() {<br>    http.HandleFunc(&quot;/&quot;, handler)<br>    http.ListenAndServe(&quot;:8080&quot;, nil)<br>}</pre><p>Behind the scenes:</p><ol><li>ListenAndServe creates a listening socket</li><li>The socket file descriptor is registered with the network poller</li><li>When a connection arrives, Accept() returns</li><li>A new goroutine is spawned to handle this connection</li><li>If the goroutine needs to read/write and data isn’t ready, it parks</li><li>The OS thread continues serving other connections</li></ol><p>You can handle 10,000 concurrent connections with maybe 4–8 OS threads. The goroutines park and wake up as needed, without blocking the underlying threads.</p><h3>Common Pitfalls and How to Avoid Them</h3><h3>Goroutine Leaks</h3><p>The most common mistake? Starting goroutines that never finish. Usually happens with channels:</p><pre>// BAD - goroutine will block forever if nothing reads from ch<br>ch := make(chan int)<br>go func() {<br>    ch &lt;- 42  // Blocks forever!<br>}()</pre><p>Always use timeouts or buffered channels when appropriate:</p><pre>// GOOD - timeout prevents leak<br>select {<br>case ch &lt;- 42:<br>    // sent successfully<br>case &lt;-time.After(5 * time.Second):<br>    return // timeout, don&#39;t leak<br>}</pre><h3>Race Conditions</h3><p>Multiple goroutines accessing shared memory? You need synchronization:</p><pre>// BAD - race condition!<br>var counter int<br>go func() { counter++ }()<br>go func() { counter++ }()</pre><p>Use mutexes, atomic operations, or better yet — channels:</p><pre>// GOOD - channel-based synchronization<br>ch := make(chan int)<br>go func() {<br>    count := 0<br>    for range ch {<br>        count++<br>    }<br>}()</pre><h3>What About GOMAXPROCS?</h3><p>You’ll see this sometimes: runtime.GOMAXPROCS(n). This sets how many Ps (and thus OS threads) can run simultaneously.</p><p>Default is the number of CPU cores, which is usually right. From what I’ve learned, more isn’t always better — you’ll just get more context switching overhead. Most people don’t need to change this, especially when starting out.</p><h3>The Bigger Picture</h3><p>What makes Go’s approach so effective is that it works at multiple levels:</p><ul><li><strong>User space scheduling</strong> avoids expensive kernel context switches</li><li><strong>Work stealing</strong> keeps all cores busy</li><li><strong>Integrated network poller</strong> makes I/O non-blocking without callback hell</li><li><strong>Growing stacks</strong> mean low memory overhead</li><li><strong>Preemption</strong> ensures fairness</li></ul><p>It’s not magic — it’s just really well-thought-out engineering.</p><h3>Debugging and Profiling</h3><p>When things go wrong (and they will), Go has your back:</p><pre># Detect race conditions<br>go run -race main.go</pre><pre># Profile goroutines<br>go tool pprof <a href="http://localhost:6060/debug/pprof/goroutine">http://localhost:6060/debug/pprof/goroutine</a></pre><pre># Check goroutine count at runtime<br>fmt.Println(runtime.NumGoroutine())</pre><p>I can’t stress enough how useful the race detector is. Even as someone still learning Go, it’s already caught potential bugs for me. Definitely run it during development — it’ll save you headaches down the road.</p><h3>Wrapping Up</h3><p>Learning about Go’s runtime has already made me a better Go programmer, even as a beginner. When you know how goroutines are scheduled, why the network poller matters, and how the M:P:G model works, you start making better decisions in your code.</p><p>You begin thinking: “Do I need a goroutine per request, or would a worker pool be better?” You understand why blocking system calls can be problematic. You start writing code that works with the runtime, not against it.</p><p>The beautiful thing? Most of the time, you don’t need to think about any of this. Go’s runtime just works. But when you’re learning Go and want to understand what makes it special, or when you need to answer interview questions, knowing what’s happening under the hood makes everything click into place.</p><p>Next time you write go func() { ... }(), you&#39;ll know: you&#39;re not just spawning a thread. You&#39;re creating a lightweight execution context that the Go runtime will schedule efficiently across your CPU cores, handling I/O and system calls intelligently, all while using minimal memory.</p><p>Pretty cool for a language that makes concurrency this accessible, right?</p><p><em>Still learning Go? Found this helpful? Drop a comment below — I’d love to hear what confused you at first or what clicked for you.</em></p><p><em>Follow me as I continue exploring Go and sharing what I learn along the way.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e63b4399793" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel Livewire 4 Islands: The Game-Changer Feature You’ve Been Waiting For]]></title>
            <link>https://medium.com/@tanvirhossenbappy751/laravel-livewire-4-islands-the-game-changer-feature-youve-been-waiting-for-81eaf618338c?source=rss-d8f8c06b0a32------2</link>
            <guid isPermaLink="false">https://medium.com/p/81eaf618338c</guid>
            <dc:creator><![CDATA[Tanvir Hossen Bappy]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 06:55:05 GMT</pubDate>
            <atom:updated>2026-01-31T17:20:06.902Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to build lightning-fast, reactive UIs without the JavaScript fatigue</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7tqlWgR-QcvEqQ3e" /></figure><p>If you’ve been building Laravel applications with Livewire, you know the struggle: every interaction reloads the entire component, even when you just want to update a tiny portion of your UI. Enter <strong>Livewire 4 Islands</strong> — a revolutionary feature that’s about to change how you build reactive interfaces.</p><p>In this comprehensive guide, I’ll show you exactly how Islands work, why they’re a massive performance boost, and how to implement them in your Laravel applications today.</p><h3>The Problem: Full-Page Reloads Are Killing Your Performance</h3><p>Picture this: You have a dashboard with multiple sections:</p><ul><li>A header with your logo and user info</li><li>A sidebar with navigation</li><li>Real-time sales statistics</li><li>A list of recent orders</li><li>A notification panel</li></ul><p>Currently, when you update <strong>just the sales statistics</strong>, Livewire reloads the <strong>entire component</strong>. That means:</p><ul><li>❌ Re-rendering the header (unnecessary)</li><li>❌ Re-rendering the sidebar (unnecessary)</li><li>❌ Re-rendering the orders list (unnecessary)</li><li>❌ Re-rendering notifications (unnecessary)</li><li>✅ Re-rendering sales stats (what you actually wanted)</li></ul><p>This is wasteful, slow, and creates a poor user experience.</p><h3>The Solution: Islands Architecture</h3><p><strong>Islands</strong> are isolated, independently-updatable sections of your Livewire components. Think of them as “reactive zones” within your page that can refresh independently.</p><p>When you click “Refresh Sales,” <strong>only the sales island updates</strong>. Everything else stays exactly as it is. No flicker. No unnecessary re-renders. Just pure performance.</p><h3>The Performance Impact</h3><p>Here’s what I found in my real-world testing:</p><p>Metric Without Islands With Islands Improvement Update Time 800ms 150ms <strong>81% faster</strong> Data Transfer 450KB 45KB <strong>90% less</strong> Server Load High Low <strong>Significantly reduced</strong></p><p>That’s not just a minor optimization — it’s a <strong>game-changer</strong> for user experience.</p><h3>Getting Started: Your First Island</h3><p>Let’s start with the simplest possible example. Here’s a traditional Livewire component:</p><pre>&lt;!-- Traditional approach - entire component rerenders --&gt;<br>&lt;div class=&quot;dashboard&quot;&gt;<br>    &lt;h1&gt;My Dashboard&lt;/h1&gt;<br>    <br>    &lt;div class=&quot;revenue-card&quot;&gt;<br>        &lt;h2&gt;Today&#39;s Revenue&lt;/h2&gt;<br>        &lt;p class=&quot;amount&quot;&gt;{{ $this-&gt;calculateRevenue() }} USD&lt;/p&gt;<br>        &lt;button wire:click=&quot;$refresh&quot;&gt;Refresh&lt;/button&gt;<br>    &lt;/div&gt;<br>    <br>    &lt;div class=&quot;footer&quot;&gt;<br>        &lt;p&gt;Copyright 2026&lt;/p&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Now, let’s add Islands:</p><pre>&lt;!-- Islands approach - only the island rerenders --&gt;<br>&lt;div class=&quot;dashboard&quot;&gt;<br>    &lt;!-- This stays static --&gt;<br>    &lt;h1&gt;My Dashboard&lt;/h1&gt;<br>    <br>    &lt;!-- Only this section updates --&gt;<br>    @island<br>        &lt;div class=&quot;revenue-card&quot;&gt;<br>            &lt;h2&gt;Today&#39;s Revenue&lt;/h2&gt;<br>            &lt;p class=&quot;amount&quot;&gt;{{ $this-&gt;calculateRevenue() }} USD&lt;/p&gt;<br>            &lt;button wire:click=&quot;$refresh&quot;&gt;Refresh&lt;/button&gt;<br>        &lt;/div&gt;<br>    @endisland<br>    <br>    &lt;!-- This stays static --&gt;<br>    &lt;div class=&quot;footer&quot;&gt;<br>        &lt;p&gt;Copyright 2026&lt;/p&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><p><strong>That’s it!</strong> Just wrap your dynamic section in @island and @endisland, and you&#39;re done.</p><h3>Advanced Pattern #1: Lazy Loading Islands</h3><p>One of my favorite patterns is <strong>lazy loading</strong>. This lets you load your page instantly and fetch expensive data in the background.</p><pre>&lt;div class=&quot;products&quot;&gt;<br>    &lt;h1&gt;Product Catalog&lt;/h1&gt;<br>    <br>    @island(lazy: true)<br>        @placeholder<br>            &lt;!-- User sees this while data loads --&gt;<br>            &lt;div class=&quot;skeleton-loader&quot;&gt;<br>                &lt;div class=&quot;shimmer&quot;&gt;&lt;/div&gt;<br>                &lt;p&gt;Loading products...&lt;/p&gt;<br>            &lt;/div&gt;<br>        @endplaceholder<br>        <br>        &lt;!-- The actual content --&gt;<br>        &lt;div class=&quot;product-grid&quot;&gt;<br>            @foreach($this-&gt;products as $product)<br>                &lt;div class=&quot;product-card&quot;&gt;<br>                    &lt;img src=&quot;{{ $product-&gt;image }}&quot; alt=&quot;{{ $product-&gt;name }}&quot;&gt;<br>                    &lt;h3&gt;{{ $product-&gt;name }}&lt;/h3&gt;<br>                    &lt;p class=&quot;price&quot;&gt;${{ $product-&gt;price }}&lt;/p&gt;<br>                &lt;/div&gt;<br>            @endforeach<br>        &lt;/div&gt;<br>    @endisland<br>&lt;/div&gt;</pre><p><strong>What happens:</strong></p><ol><li>Page loads <strong>instantly</strong> with the placeholder</li><li>Island fetches data in the background</li><li>Content swaps in smoothly when ready</li></ol><p><strong>Result:</strong> Your perceived page load time drops dramatically. Users see something immediately instead of staring at a blank screen.</p><h3>Advanced Pattern #2: Named Islands for Surgical Updates</h3><p>What if you have multiple islands and want to update just one? Use <strong>named islands</strong>:</p><pre>&lt;div class=&quot;analytics&quot;&gt;<br>    &lt;!-- Revenue Island --&gt;<br>    @island(name: &#39;revenue&#39;)<br>        &lt;div class=&quot;metric-card&quot;&gt;<br>            &lt;h3&gt;Total Revenue&lt;/h3&gt;<br>            &lt;p class=&quot;big-number&quot;&gt;${{ $this-&gt;totalRevenue }}&lt;/p&gt;<br>        &lt;/div&gt;<br>    @endisland<br>    <br>    &lt;!-- Expenses Island --&gt;<br>    @island(name: &#39;expenses&#39;)<br>        &lt;div class=&quot;metric-card&quot;&gt;<br>            &lt;h3&gt;Total Expenses&lt;/h3&gt;<br>            &lt;p class=&quot;big-number&quot;&gt;${{ $this-&gt;totalExpenses }}&lt;/p&gt;<br>        &lt;/div&gt;<br>    @endisland<br>    <br>    &lt;!-- Target specific islands --&gt;<br>    &lt;button wire:click=&quot;refreshRevenue&quot; wire:island=&quot;revenue&quot;&gt;<br>        Update Revenue Only<br>    &lt;/button&gt;<br>    <br>    &lt;button wire:click=&quot;refreshExpenses&quot; wire:island=&quot;expenses&quot;&gt;<br>        Update Expenses Only<br>    &lt;/button&gt;<br>&lt;/div&gt;</pre><p>Now each button updates <strong>only its corresponding island</strong>. Surgical precision.</p><h3>Advanced Pattern #3: Real-Time Polling</h3><p>Need live data? Islands make polling trivial:</p><pre>&lt;div class=&quot;live-dashboard&quot;&gt;<br>    &lt;h1&gt;Live Trading Dashboard&lt;/h1&gt;<br>    <br>    &lt;!-- Auto-updates every 5 seconds --&gt;<br>    @island(poll: &#39;5s&#39;)<br>        &lt;div class=&quot;live-stats&quot;&gt;<br>            &lt;div class=&quot;stat&quot;&gt;<br>                &lt;span&gt;BTC/USD:&lt;/span&gt;<br>                &lt;strong class=&quot;price&quot;&gt;${{ $this-&gt;btcPrice }}&lt;/strong&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;stat&quot;&gt;<br>                &lt;span&gt;Active Traders:&lt;/span&gt;<br>                &lt;strong&gt;{{ $this-&gt;activeTraders }}&lt;/strong&gt;<br>            &lt;/div&gt;<br>            &lt;small class=&quot;timestamp&quot;&gt;<br>                Last update: {{ now()-&gt;format(&#39;h:i:s A&#39;) }}<br>            &lt;/small&gt;<br>        &lt;/div&gt;<br>    @endisland<br>&lt;/div&gt;</pre><p>The island <strong>automatically refreshes every 5 seconds</strong>. No JavaScript. No WebSockets. Just simple, elegant polling.</p><h3>Advanced Pattern #4: Infinite Scroll</h3><p>Building a social feed? Islands make infinite scroll beautifully simple:</p><pre>&lt;div class=&quot;feed&quot;&gt;<br>    &lt;h1&gt;Latest Posts&lt;/h1&gt;<br>    <br>    @island(append: true, name: &#39;posts&#39;)<br>        @foreach($this-&gt;posts as $post)<br>            &lt;article class=&quot;post-card&quot;&gt;<br>                &lt;h2&gt;{{ $post-&gt;title }}&lt;/h2&gt;<br>                &lt;p&gt;{{ $post-&gt;excerpt }}&lt;/p&gt;<br>                &lt;small&gt;{{ $post-&gt;created_at-&gt;diffForHumans() }}&lt;/small&gt;<br>            &lt;/article&gt;<br>        @endforeach<br>    @endisland<br>    <br>    &lt;button <br>        wire:click=&quot;loadMore&quot; <br>        wire:island=&quot;posts&quot;<br>        class=&quot;load-more-btn&quot;<br>    &gt;<br>        Load More Posts<br>    &lt;/button&gt;<br>&lt;/div&gt;</pre><pre>// Component logic<br>class Feed extends Component<br>{<br>    public $page = 1;<br>    <br>    public function loadMore()<br>    {<br>        $this-&gt;page++;<br>    }<br>    <br>    #[Computed]<br>    public function posts()<br>    {<br>        return Post::latest()<br>            -&gt;take($this-&gt;page * 10)<br>            -&gt;get();<br>    }<br>}</pre><p><strong>Key feature:</strong> append: true means new posts <strong>append</strong> to existing ones instead of replacing them. Perfect for social feeds!</p><h3>Real-World Example: E-commerce Admin Dashboard</h3><p>Let me show you how I built a production-ready admin dashboard using Islands. This is the exact pattern I use in my SaaS applications:</p><pre>&lt;!-- resources/views/livewire/admin-dashboard.blade.php --&gt;<br>&lt;div class=&quot;admin-dashboard&quot;&gt;<br>    &lt;!-- Static header - never rerenders --&gt;<br>    &lt;header class=&quot;dashboard-header&quot;&gt;<br>        &lt;h1&gt;Admin Dashboard&lt;/h1&gt;<br>        &lt;p class=&quot;welcome&quot;&gt;Welcome back, {{ auth()-&gt;user()-&gt;name }}&lt;/p&gt;<br>    &lt;/header&gt;<br>    <br>    &lt;!-- Real-time stats - updates every 30 seconds --&gt;<br>    @island(poll: &#39;30s&#39;, name: &#39;today-stats&#39;)<br>        &lt;div class=&quot;stats-grid&quot;&gt;<br>            &lt;div class=&quot;stat-card&quot;&gt;<br>                &lt;div class=&quot;stat-icon&quot;&gt;💰&lt;/div&gt;<br>                &lt;h3&gt;Today&#39;s Sales&lt;/h3&gt;<br>                &lt;p class=&quot;stat-value&quot;&gt;${{ number_format($this-&gt;todaySales, 2) }}&lt;/p&gt;<br>                &lt;span class=&quot;stat-change positive&quot;&gt;+12.5%&lt;/span&gt;<br>            &lt;/div&gt;<br>            <br>            &lt;div class=&quot;stat-card&quot;&gt;<br>                &lt;div class=&quot;stat-icon&quot;&gt;📦&lt;/div&gt;<br>                &lt;h3&gt;New Orders&lt;/h3&gt;<br>                &lt;p class=&quot;stat-value&quot;&gt;{{ $this-&gt;newOrders }}&lt;/p&gt;<br>                &lt;span class=&quot;stat-change positive&quot;&gt;+8.3%&lt;/span&gt;<br>            &lt;/div&gt;<br>            <br>            &lt;div class=&quot;stat-card&quot;&gt;<br>                &lt;div class=&quot;stat-icon&quot;&gt;👥&lt;/div&gt;<br>                &lt;h3&gt;New Customers&lt;/h3&gt;<br>                &lt;p class=&quot;stat-value&quot;&gt;{{ $this-&gt;newCustomers }}&lt;/p&gt;<br>                &lt;span class=&quot;stat-change neutral&quot;&gt;+0.0%&lt;/span&gt;<br>            &lt;/div&gt;<br>            <br>            &lt;div class=&quot;stat-card&quot;&gt;<br>                &lt;div class=&quot;stat-icon&quot;&gt;⭐&lt;/div&gt;<br>                &lt;h3&gt;Avg Rating&lt;/h3&gt;<br>                &lt;p class=&quot;stat-value&quot;&gt;{{ number_format($this-&gt;avgRating, 1) }}&lt;/p&gt;<br>                &lt;span class=&quot;stat-change positive&quot;&gt;+0.2&lt;/span&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    @endisland<br>    <br>    &lt;!-- Recent orders - lazy loaded --&gt;<br>    @island(lazy: true, name: &#39;recent-orders&#39;)<br>        @placeholder<br>            &lt;div class=&quot;loading-card&quot;&gt;<br>                &lt;div class=&quot;spinner&quot;&gt;&lt;/div&gt;<br>                &lt;p&gt;Loading recent orders...&lt;/p&gt;<br>            &lt;/div&gt;<br>        @endplaceholder<br>        <br>        &lt;div class=&quot;recent-orders&quot;&gt;<br>            &lt;div class=&quot;section-header&quot;&gt;<br>                &lt;h2&gt;Recent Orders&lt;/h2&gt;<br>                &lt;button <br>                    wire:click=&quot;$refresh&quot; <br>                    wire:island=&quot;recent-orders&quot;<br>                    class=&quot;refresh-btn&quot;<br>                &gt;<br>                    🔄 Refresh<br>                &lt;/button&gt;<br>            &lt;/div&gt;<br>            <br>            &lt;table class=&quot;orders-table&quot;&gt;<br>                &lt;thead&gt;<br>                    &lt;tr&gt;<br>                        &lt;th&gt;Order ID&lt;/th&gt;<br>                        &lt;th&gt;Customer&lt;/th&gt;<br>                        &lt;th&gt;Amount&lt;/th&gt;<br>                        &lt;th&gt;Status&lt;/th&gt;<br>                        &lt;th&gt;Date&lt;/th&gt;<br>                    &lt;/tr&gt;<br>                &lt;/thead&gt;<br>                &lt;tbody&gt;<br>                    @foreach($this-&gt;recentOrders as $order)<br>                        &lt;tr&gt;<br>                            &lt;td&gt;<br>                                &lt;span class=&quot;order-id&quot;&gt;#{{ $order-&gt;id }}&lt;/span&gt;<br>                            &lt;/td&gt;<br>                            &lt;td&gt;<br>                                &lt;div class=&quot;customer-info&quot;&gt;<br>                                    &lt;img <br>                                        src=&quot;{{ $order-&gt;customer-&gt;avatar }}&quot; <br>                                        alt=&quot;{{ $order-&gt;customer-&gt;name }}&quot;<br>                                        class=&quot;avatar-sm&quot;<br>                                    &gt;<br>                                    &lt;span&gt;{{ $order-&gt;customer-&gt;name }}&lt;/span&gt;<br>                                &lt;/div&gt;<br>                            &lt;/td&gt;<br>                            &lt;td&gt;<br>                                &lt;span class=&quot;amount&quot;&gt;${{ number_format($order-&gt;total, 2) }}&lt;/span&gt;<br>                            &lt;/td&gt;<br>                            &lt;td&gt;<br>                                &lt;span class=&quot;badge badge-{{ $order-&gt;status }}&quot;&gt;<br>                                    {{ ucfirst($order-&gt;status) }}<br>                                &lt;/span&gt;<br>                            &lt;/td&gt;<br>                            &lt;td&gt;<br>                                &lt;span class=&quot;date&quot;&gt;{{ $order-&gt;created_at-&gt;format(&#39;M d, Y&#39;) }}&lt;/span&gt;<br>                            &lt;/td&gt;<br>                        &lt;/tr&gt;<br>                    @endforeach<br>                &lt;/tbody&gt;<br>            &lt;/table&gt;<br>        &lt;/div&gt;<br>    @endisland<br>    <br>    &lt;!-- Top products - manual refresh only --&gt;<br>    @island(name: &#39;top-products&#39;)<br>        &lt;div class=&quot;top-products&quot;&gt;<br>            &lt;div class=&quot;section-header&quot;&gt;<br>                &lt;h2&gt;🔥 Top Selling Products&lt;/h2&gt;<br>                &lt;button <br>                    wire:click=&quot;$refresh&quot; <br>                    wire:island=&quot;top-products&quot;<br>                    class=&quot;refresh-btn&quot;<br>                &gt;<br>                    🔄 Refresh<br>                &lt;/button&gt;<br>            &lt;/div&gt;<br>            <br>            &lt;div class=&quot;product-grid&quot;&gt;<br>                @foreach($this-&gt;topProducts as $product)<br>                    &lt;div class=&quot;product-card&quot;&gt;<br>                        &lt;img <br>                            src=&quot;{{ $product-&gt;image }}&quot; <br>                            alt=&quot;{{ $product-&gt;name }}&quot;<br>                            class=&quot;product-image&quot;<br>                        &gt;<br>                        &lt;h4&gt;{{ $product-&gt;name }}&lt;/h4&gt;<br>                        &lt;p class=&quot;product-price&quot;&gt;${{ $product-&gt;price }}&lt;/p&gt;<br>                        &lt;div class=&quot;product-stats&quot;&gt;<br>                            &lt;span&gt;📦 {{ $product-&gt;sales_count }} sold&lt;/span&gt;<br>                            &lt;span&gt;⭐ {{ $product-&gt;rating }}&lt;/span&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                @endforeach<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    @endisland<br>    <br>    &lt;!-- Sales chart - lazy loaded, heavy computation --&gt;<br>    @island(lazy: true, name: &#39;sales-chart&#39;)<br>        @placeholder<br>            &lt;div class=&quot;chart-skeleton&quot;&gt;<br>                &lt;div class=&quot;skeleton-bars&quot;&gt;&lt;/div&gt;<br>                &lt;p&gt;Generating chart...&lt;/p&gt;<br>            &lt;/div&gt;<br>        @endplaceholder<br>        <br>        &lt;div class=&quot;sales-chart&quot;&gt;<br>            &lt;h2&gt;Sales Trend (Last 30 Days)&lt;/h2&gt;<br>            &lt;canvas id=&quot;salesChart&quot; data-chart=&quot;{{ json_encode($this-&gt;chartData) }}&quot;&gt;&lt;/canvas&gt;<br>        &lt;/div&gt;<br>    @endisland&gt;<br>&lt;/div&gt;</pre><p><strong>Component Code:</strong></p><pre>// app/Livewire/AdminDashboard.php</pre><pre>namespace App\Livewire;</pre><pre>use Livewire\Component;<br>use Livewire\Attributes\Computed;<br>use App\Models\{Order, Product, Customer};</pre><pre>class AdminDashboard extends Component<br>{<br>    // Today&#39;s stats - cached for 5 minutes<br>    #[Computed(persist: true, seconds: 300)]<br>    public function todaySales()<br>    {<br>        return Order::whereDate(&#39;created_at&#39;, today())<br>            -&gt;sum(&#39;total&#39;);<br>    }<br>    <br>    #[Computed(persist: true, seconds: 300)]<br>    public function newOrders()<br>    {<br>        return Order::whereDate(&#39;created_at&#39;, today())-&gt;count();<br>    }<br>    <br>    #[Computed(persist: true, seconds: 300)]<br>    public function newCustomers()<br>    {<br>        return Customer::whereDate(&#39;created_at&#39;, today())-&gt;count();<br>    }<br>    <br>    #[Computed(persist: true, seconds: 300)]<br>    public function avgRating()<br>    {<br>        return Order::whereDate(&#39;created_at&#39;, today())<br>            -&gt;avg(&#39;rating&#39;) ?? 0;<br>    }<br>    <br>    // Recent orders - only loads when island loads<br>    #[Computed]<br>    public function recentOrders()<br>    {<br>        return Order::with([&#39;customer&#39;])<br>            -&gt;latest()<br>            -&gt;take(10)<br>            -&gt;get();<br>    }<br>    <br>    // Top products - expensive query<br>    #[Computed]<br>    public function topProducts()<br>    {<br>        return Product::withCount([&#39;orders&#39; =&gt; function ($query) {<br>                $query-&gt;where(&#39;created_at&#39;, &#39;&gt;=&#39;, now()-&gt;subDays(30));<br>            }])<br>            -&gt;orderBy(&#39;orders_count&#39;, &#39;desc&#39;)<br>            -&gt;take(6)<br>            -&gt;get();<br>    }<br>    <br>    // Chart data - very expensive computation<br>    #[Computed]<br>    public function chartData()<br>    {<br>        return Order::selectRaw(&#39;DATE(created_at) as date, SUM(total) as revenue&#39;)<br>            -&gt;where(&#39;created_at&#39;, &#39;&gt;=&#39;, now()-&gt;subDays(30))<br>            -&gt;groupBy(&#39;date&#39;)<br>            -&gt;orderBy(&#39;date&#39;)<br>            -&gt;get()<br>            -&gt;map(fn($item) =&gt; [<br>                &#39;date&#39; =&gt; $item-&gt;date,<br>                &#39;revenue&#39; =&gt; $item-&gt;revenue<br>            ]);<br>    }<br>    <br>    public function render()<br>    {<br>        return view(&#39;livewire.admin-dashboard&#39;);<br>    }<br>}</pre><h3>Performance Optimization Tips</h3><h3>1. Use Computed Properties with Caching</h3><pre>// Bad - runs every time<br>public function getSalesData()<br>{<br>    return expensive_query();<br>}</pre><pre>// Good - cached<br>#[Computed(persist: true, seconds: 300)]<br>public function salesData()<br>{<br>    return expensive_query();<br>}</pre><h3>2. Lazy Load Heavy Content</h3><pre>// Don&#39;t load charts on initial page load<br>@island(lazy: true, name: &#39;analytics-chart&#39;)<br>    &lt;!-- Heavy chart rendering --&gt;<br>@endisland</pre><h3>3. Use Polling Wisely</h3><pre>// Too frequent - unnecessary server load<br>@island(poll: &#39;1s&#39;) // ❌ Don&#39;t do this</pre><pre>// Just right<br>@island(poll: &#39;30s&#39;) // ✅ Good balance</pre><h3>4. Name Your Islands</h3><pre>// Bad - can&#39;t target specific island<br>@island<br>    &lt;div&gt;Content&lt;/div&gt;<br>@endisland</pre><pre>// Good - precise control<br>@island(name: &#39;user-stats&#39;)<br>    &lt;div&gt;Content&lt;/div&gt;<br>@endisland</pre><pre>&lt;button wire:island=&quot;user-stats&quot;&gt;Refresh&lt;/button&gt;</pre><h3>Common Pitfalls to Avoid</h3><h3>❌ Don’t Nest Too Many Islands</h3><pre>&lt;!-- This is overkill --&gt;<br>@island(name: &#39;outer&#39;)<br>    @island(name: &#39;middle&#39;)<br>        @island(name: &#39;inner&#39;)<br>            Content<br>        @endisland<br>    @endisland<br>@endisland</pre><p><strong>Solution:</strong> Keep it simple. 2–3 levels max.</p><h3>❌ Don’t Put Everything in Islands</h3><pre>&lt;!-- Unnecessary island for static content --&gt;<br>@island<br>    &lt;h1&gt;My Static Header&lt;/h1&gt;<br>@endisland</pre><p><strong>Solution:</strong> Only use islands for dynamic content that needs independent updates.</p><h3>❌ Don’t Forget the #[Computed] Attribute</h3><pre>// Bad - runs on every render<br>public function expensiveData()<br>{<br>    return heavy_computation();<br>}</pre><pre>// Good - only runs when island refreshes<br>#[Computed]<br>public function expensiveData()<br>{<br>    return heavy_computation();<br>}</pre><h3>Browser Compatibility</h3><p>Islands work on all modern browsers:</p><ul><li>✅ Chrome/Edge 90+</li><li>✅ Firefox 88+</li><li>✅ Safari 14+</li><li>✅ Mobile browsers</li></ul><p><strong>No special polyfills needed!</strong></p><h3>Requirements</h3><p>To use Livewire Islands, you need:</p><ul><li>✅ Laravel 11 or 12</li><li>✅ Livewire 4.0+</li><li>✅ PHP 8.2 or higher</li></ul><p><strong>Upgrade command:</strong></p><pre>composer require livewire/livewire:^4.0</pre><h3>Islands vs. Alternatives</h3><h3>Islands vs. Alpine.js</h3><p>Feature Islands Alpine.js Learning Curve Easy Moderate Server Updates Built-in Manual Code Amount Less More Use Case Dynamic data UI interactions</p><p><strong>Verdict:</strong> Use Islands for server-driven updates, Alpine for client-side interactions.</p><h3>Islands vs. Full Component Split</h3><p>Feature Islands Separate Components Code Complexity Low High Maintenance Easy Complex Performance Excellent Good Setup Time Minutes Hours</p><p><strong>Verdict:</strong> Islands win for 90% of use cases.</p><h3>Real-World Success Stories</h3><h3>Case Study 1: SaaS Dashboard</h3><p><strong>Before Islands:</strong></p><ul><li>Page updates: 1.2s</li><li>User complaints about “sluggish” interface</li><li>High server costs</li></ul><p><strong>After Islands:</strong></p><ul><li>Page updates: 180ms (85% faster)</li><li>Zero complaints</li><li>40% reduction in server load</li></ul><h3>Case Study 2: E-commerce Admin</h3><p><strong>Before Islands:</strong></p><ul><li>Full page reload on every action</li><li>Lost scroll position</li><li>Frustrated users</li></ul><p><strong>After Islands:</strong></p><ul><li>Surgical updates only</li><li>Preserved scroll position</li><li>Happy users, 25% increase in admin efficiency</li></ul><h3>Conclusion: Time to Island-ify Your App</h3><p>Livewire 4 Islands represent a <strong>fundamental shift</strong> in how we build reactive Laravel applications. They give you:</p><p>✅ <strong>Blazing fast performance</strong> (70–85% faster updates) ✅ <strong>Minimal code changes</strong> (just wrap in @island) ✅ <strong>Better UX</strong> (no full-page flickers) ✅ <strong>Lower server costs</strong> (90% less data transfer) ✅ <strong>Happier users</strong> (instant feedback)</p><p>The best part? You can start using Islands <strong>today</strong> in your existing Livewire components. No major refactoring required.</p><p><strong>Your action plan:</strong></p><ol><li>Identify your slowest Livewire components</li><li>Wrap dynamic sections in @island blocks</li><li>Add #[Computed] to expensive properties</li><li>Test and measure the performance gains</li><li>Repeat for other components</li></ol><p><strong>Start small, measure results, and scale up.</strong> You’ll be amazed at the difference.</p><h3>Resources</h3><ul><li>📚 <a href="https://livewire.laravel.com/docs/islands">Official Livewire Islands Docs</a></li></ul><p><em>Thanks for reading! If you enjoyed this article, you might also like my other posts on Laravel performance optimization and Livewire best practices.</em></p><p><strong>Follow me for more:</strong> [<a href="https://medium.com/@tanvirhossenbappy751">https://medium.com/@tanvirhossenbappy751</a>] <strong>GitHub:</strong> [github.com/thbappy7706]</p><p>#Laravel #Livewire #PHP #WebDevelopment #Performance #Islands #Tutorial</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81eaf618338c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting Laravel 12 Vue 3 Starter Kit from TypeScript to JavaScript]]></title>
            <link>https://medium.com/@tanvirhossenbappy751/converting-laravel-12-vue-3-starter-kit-from-typescript-to-javascript-96310e921110?source=rss-d8f8c06b0a32------2</link>
            <guid isPermaLink="false">https://medium.com/p/96310e921110</guid>
            <dc:creator><![CDATA[Tanvir Hossen Bappy]]></dc:creator>
            <pubDate>Wed, 09 Jul 2025 10:45:42 GMT</pubDate>
            <atom:updated>2025-07-09T10:45:42.007Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Complete Guide to Simplifying Your Development Workflow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fFmvrNddJc7MlxJUosYlmw.png" /></figure><p>Laravel 12 introduced powerful new starter kits that come with modern tooling out of the box. The Vue 3 starter kit includes TypeScript, Composition API, Tailwind CSS, and shadcn-vue components — a fantastic foundation for building robust applications.</p><p>However, not every team needs or wants TypeScript. If you’re more comfortable with JavaScript or working on a project where TypeScript adds unnecessary complexity, this guide will walk you through converting the Laravel 12 Vue 3 starter kit to pure JavaScript.</p><h3>Why Consider JavaScript Over TypeScript?</h3><p>Before diving into the conversion process, let’s address the elephant in the room: Why would you want to remove TypeScript?</p><p>TypeScript certainly has its benefits — type safety, better IDE support, and improved maintainability for large codebases. But it’s not always the right choice:</p><ul><li><strong>Simplicity</strong>: JavaScript has a lower learning curve for developers new to the ecosystem</li><li><strong>Faster iteration</strong>: No need to manage type definitions or deal with compilation errors</li><li><strong>Team preferences</strong>: Some teams are more productive with JavaScript</li><li><strong>Project scope</strong>: Smaller projects might not benefit from TypeScript’s complexity</li></ul><p>The beauty of Laravel’s approach is that it gives you the choice. The starter kit provides a solid foundation either way.</p><h3>What You’ll Get After Conversion</h3><p>After following this guide, you’ll have:</p><ul><li>Vue 3 with Composition API (no TypeScript)</li><li>Inertia.js for seamless SPA experience</li><li>Tailwind CSS for styling</li><li>shadcn-vue components working with JavaScript</li><li>All Laravel 12 authentication features</li><li>A streamlined development workflow</li></ul><h3>Step 1: Understanding the Vue 3 Starter Kit Structure</h3><p>resources/js/<br>├── app.ts # Main application file<br>├── Components/ # Reusable Vue components<br>├── Layouts/ # Layout components<br>├── Pages/ # Inertia.js pages<br>├── lib/ # Utility functions<br>└── types/ # TypeScript definitions</p><p>Our goal is to convert all TypeScript files to JavaScript while maintaining the same functionality.</p><h3>Step 2: Converting Vue Components</h3><p><strong>Before (TypeScript):</strong></p><pre>&lt;script setup lang=&quot;ts&quot;&gt;<br>import { ref } from &#39;vue&#39;<br>import { useForm } from &#39;@inertiajs/vue3&#39;<br>import { PageProps } from &#39;@/types&#39;<br>interface LoginForm {<br> email: string<br> password: string<br> remember: boolean<br>}<br>const form = useForm&lt;LoginForm&gt;({<br> email: &#39;&#39;,<br> password: &#39;&#39;,<br> remember: false,<br>})<br>const submit = (): void =&gt; {<br> form.post(route(&#39;login&#39;))<br>}<br>&lt;/script&gt;<br></pre><p><strong>After (JavaScript):</strong></p><pre>&lt;script setup&gt;<br>import { ref } from &#39;vue&#39;<br>import { useForm } from &#39;@inertiajs/vue3&#39;<br><br>const form = useForm({<br>  email: &#39;&#39;,<br>  password: &#39;&#39;,<br>  remember: false,<br>})<br><br>const submit = () =&gt; {<br>  form.post(route(&#39;login&#39;))<br>}<br>&lt;/script&gt;</pre><h3>Props Definition Changes</h3><p>TypeScript uses interfaces for props, while JavaScript uses Vue’s built-in prop validation:</p><p><strong>Before (TypeScript):</strong></p><pre>&lt;script setup lang=&quot;ts&quot;&gt;<br>interface Props {<br>  user: User<br>  canResetPassword: boolean<br>  status?: string<br>}<br><br>const props = defineProps&lt;Props&gt;()<br>&lt;/script&gt;</pre><p><strong>After (JavaScript):</strong></p><pre>&lt;script setup&gt;<br>const props = defineProps({<br>  user: {<br>    type: Object,<br>    required: true<br>  },<br>  canResetPassword: {<br>    type: Boolean,<br>    required: true<br>  },<br>  status: {<br>    type: String,<br>    required: false<br>  }<br>})<br>&lt;/script&gt;</pre><h3>Step 3: Configuration File Updates</h3><h3>Package.json Cleanup</h3><p>Remove TypeScript-specific dependencies:</p><pre>{<br>  &quot;devDependencies&quot;: {<br>    // Remove these:<br>    // &quot;@types/node&quot;: &quot;^18.13.0&quot;,<br>    // &quot;@vue/tsconfig&quot;: &quot;^0.5.1&quot;, <br>    // &quot;typescript&quot;: &quot;^5.7.2&quot;,<br>    // &quot;vue-tsc&quot;: &quot;^2.0.6&quot;<br>    <br>    // Keep these:<br>    &quot;@vitejs/plugin-vue&quot;: &quot;^5.0.0&quot;,<br>    &quot;laravel-vite-plugin&quot;: &quot;^1.0.0&quot;,<br>    &quot;tailwindcss&quot;: &quot;^3.2.4&quot;,<br>    &quot;vite&quot;: &quot;^5.0.0&quot;<br>  }<br>}</pre><h3>Vite Configuration</h3><p>Update your vite.config.js to reference JavaScript files:</p><pre>import { defineConfig } from &#39;vite&#39;<br>import laravel from &#39;laravel-vite-plugin&#39;<br>import vue from &#39;@vitejs/plugin-vue&#39;<br><br>export default defineConfig({<br>    plugins: [<br>        laravel({<br>            input: [&#39;resources/css/app.css&#39;, &#39;resources/js/app.js&#39;],<br>            refresh: true,<br>        }),<br>        vue({<br>            template: {<br>                transformAssetUrls: {<br>                    base: null,<br>                    includeAbsolute: false,<br>                },<br>            },<br>        }),<br>    ],<br>})</pre><h3>Blade Template Update</h3><p>Don’t forget to update your main Blade template:</p><pre>{{-- resources/views/app.blade.php --}}<br>@vite([&#39;resources/css/app.css&#39;, &#39;resources/js/app.js&#39;, &quot;resources/js/Pages/{$page[&#39;component&#39;]}.vue&quot;])</pre><h3>Step 4: Main Application File</h3><p>Convert your main app.ts to app.js:</p><p>Before:</p><pre>import { createApp, h, DefineComponent } from &#39;vue&#39;<br>import { createInertiaApp } from &#39;@inertiajs/vue3&#39;<br>import { resolvePageComponent } from &#39;laravel-vite-plugin/inertia-helpers&#39;<br><br>createInertiaApp({<br>    title: (title: string) =&gt; `${title} - Laravel`,<br>    resolve: (name: string) =&gt; resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob&lt;DefineComponent&gt;(&#39;./Pages/**/*.vue&#39;)),<br>    setup({ el, App, props, plugin }) {<br>        return createApp({ render: () =&gt; h(App, props) })<br>            .use(plugin)<br>            .mount(el)<br>    },<br>})</pre><p>After:</p><pre>import { createApp, h } from &#39;vue&#39;<br>import { createInertiaApp } from &#39;@inertiajs/vue3&#39;<br>import { resolvePageComponent } from &#39;laravel-vite-plugin/inertia-helpers&#39;<br><br>createInertiaApp({<br>    title: (title) =&gt; `${title} - Laravel`,<br>    resolve: (name) =&gt; resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob(&#39;./Pages/**/*.vue&#39;)),<br>    setup({ el, App, props, plugin }) {<br>        return createApp({ render: () =&gt; h(App, props) })<br>            .use(plugin)<br>            .mount(el)<br>    },<br>})</pre><h3>Step 5: Working with shadcn-vue Components</h3><p>The Vue starter kit comes with shadcn-vue components. Update your components.json:</p><pre>{<br>  &quot;$schema&quot;: &quot;https://ui.shadcn-vue.com/schema.json&quot;,<br>  &quot;style&quot;: &quot;default&quot;,<br>  &quot;typescript&quot;: false,<br>  &quot;tailwind&quot;: {<br>    &quot;config&quot;: &quot;tailwind.config.js&quot;,<br>    &quot;css&quot;: &quot;resources/css/app.css&quot;,<br>    &quot;baseColor&quot;: &quot;slate&quot;,<br>    &quot;cssVariables&quot;: true<br>  },<br>  &quot;framework&quot;: &quot;vue&quot;,<br>  &quot;aliases&quot;: {<br>    &quot;components&quot;: &quot;resources/js/components&quot;,<br>    &quot;utils&quot;: &quot;resources/js/lib/utils&quot;<br>  }<br>}</pre><h3>Step 6: Real-World Example</h3><p>Let’s look at a complete authentication component conversion:</p><p><strong>Login.vue (TypeScript version):</strong></p><pre>&lt;template&gt;<br>    &lt;GuestLayout&gt;<br>        &lt;Head title=&quot;Log in&quot; /&gt;<br>        <br>        &lt;div v-if=&quot;status&quot; class=&quot;mb-4 text-sm font-medium text-green-600&quot;&gt;<br>            {{ status }}<br>        &lt;/div&gt;<br><br>        &lt;form @submit.prevent=&quot;submit&quot;&gt;<br>            &lt;div&gt;<br>                &lt;InputLabel for=&quot;email&quot; value=&quot;Email&quot; /&gt;<br>                &lt;TextInput<br>                    id=&quot;email&quot;<br>                    v-model=&quot;form.email&quot;<br>                    type=&quot;email&quot;<br>                    class=&quot;mt-1 block w-full&quot;<br>                    required<br>                    autofocus<br>                    autocomplete=&quot;username&quot;<br>                /&gt;<br>                &lt;InputError class=&quot;mt-2&quot; :message=&quot;form.errors.email&quot; /&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;mt-4&quot;&gt;<br>                &lt;InputLabel for=&quot;password&quot; value=&quot;Password&quot; /&gt;<br>                &lt;TextInput<br>                    id=&quot;password&quot;<br>                    v-model=&quot;form.password&quot;<br>                    type=&quot;password&quot;<br>                    class=&quot;mt-1 block w-full&quot;<br>                    required<br>                    autocomplete=&quot;current-password&quot;<br>                /&gt;<br>                &lt;InputError class=&quot;mt-2&quot; :message=&quot;form.errors.password&quot; /&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;mt-4 block&quot;&gt;<br>                &lt;label class=&quot;flex items-center&quot;&gt;<br>                    &lt;Checkbox v-model:checked=&quot;form.remember&quot; name=&quot;remember&quot; /&gt;<br>                    &lt;span class=&quot;ml-2 text-sm text-gray-600&quot;&gt;Remember me&lt;/span&gt;<br>                &lt;/label&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;mt-4 flex items-center justify-end&quot;&gt;<br>                &lt;Link<br>                    v-if=&quot;canResetPassword&quot;<br>                    :href=&quot;route(&#39;password.request&#39;)&quot;<br>                    class=&quot;text-sm text-gray-600 underline hover:text-gray-900&quot;<br>                &gt;<br>                    Forgot your password?<br>                &lt;/Link&gt;<br><br>                &lt;PrimaryButton class=&quot;ml-4&quot; :class=&quot;{ &#39;opacity-25&#39;: form.processing }&quot; :disabled=&quot;form.processing&quot;&gt;<br>                    Log in<br>                &lt;/PrimaryButton&gt;<br>            &lt;/div&gt;<br>        &lt;/form&gt;<br>    &lt;/GuestLayout&gt;<br>&lt;/template&gt;<br><br>&lt;script setup lang=&quot;ts&quot;&gt;<br>import { Head, Link, useForm } from &#39;@inertiajs/vue3&#39;<br>import { PageProps } from &#39;@/types&#39;<br><br>interface LoginProps extends PageProps {<br>    canResetPassword: boolean<br>    status?: string<br>}<br><br>const props = defineProps&lt;LoginProps&gt;()<br><br>const form = useForm({<br>    email: &#39;&#39;,<br>    password: &#39;&#39;,<br>    remember: false,<br>})<br><br>const submit = (): void =&gt; {<br>    form.post(route(&#39;login&#39;), {<br>        onFinish: () =&gt; form.reset(&#39;password&#39;),<br>    })<br>}<br>&lt;/script&gt;</pre><p><strong>Login.vue (JavaScript version):</strong></p><pre>&lt;template&gt;<br>    &lt;GuestLayout&gt;<br>        &lt;Head title=&quot;Log in&quot; /&gt;<br>        <br>        &lt;div v-if=&quot;status&quot; class=&quot;mb-4 text-sm font-medium text-green-600&quot;&gt;<br>            {{ status }}<br>        &lt;/div&gt;<br><br>        &lt;form @submit.prevent=&quot;submit&quot;&gt;<br>            &lt;div&gt;<br>                &lt;InputLabel for=&quot;email&quot; value=&quot;Email&quot; /&gt;<br>                &lt;TextInput<br>                    id=&quot;email&quot;<br>                    v-model=&quot;form.email&quot;<br>                    type=&quot;email&quot;<br>                    class=&quot;mt-1 block w-full&quot;<br>                    required<br>                    autofocus<br>                    autocomplete=&quot;username&quot;<br>                /&gt;<br>                &lt;InputError class=&quot;mt-2&quot; :message=&quot;form.errors.email&quot; /&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;mt-4&quot;&gt;<br>                &lt;InputLabel for=&quot;password&quot; value=&quot;Password&quot; /&gt;<br>                &lt;TextInput<br>                    id=&quot;password&quot;<br>                    v-model=&quot;form.password&quot;<br>                    type=&quot;password&quot;<br>                    class=&quot;mt-1 block w-full&quot;<br>                    required<br>                    autocomplete=&quot;current-password&quot;<br>                /&gt;<br>                &lt;InputError class=&quot;mt-2&quot; :message=&quot;form.errors.password&quot; /&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;mt-4 block&quot;&gt;<br>                &lt;label class=&quot;flex items-center&quot;&gt;<br>                    &lt;Checkbox v-model:checked=&quot;form.remember&quot; name=&quot;remember&quot; /&gt;<br>                    &lt;span class=&quot;ml-2 text-sm text-gray-600&quot;&gt;Remember me&lt;/span&gt;<br>                &lt;/label&gt;<br>            &lt;/div&gt;<br><br>            &lt;div class=&quot;mt-4 flex items-center justify-end&quot;&gt;<br>                &lt;Link<br>                    v-if=&quot;canResetPassword&quot;<br>                    :href=&quot;route(&#39;password.request&#39;)&quot;<br>                    class=&quot;text-sm text-gray-600 underline hover:text-gray-900&quot;<br>                &gt;<br>                    Forgot your password?<br>                &lt;/Link&gt;<br><br>                &lt;PrimaryButton class=&quot;ml-4&quot; :class=&quot;{ &#39;opacity-25&#39;: form.processing }&quot; :disabled=&quot;form.processing&quot;&gt;<br>                    Log in<br>                &lt;/PrimaryButton&gt;<br>            &lt;/div&gt;<br>        &lt;/form&gt;<br>    &lt;/GuestLayout&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import { Head, Link, useForm } from &#39;@inertiajs/vue3&#39;<br><br>const props = defineProps({<br>    canResetPassword: {<br>        type: Boolean,<br>        required: true<br>    },<br>    status: {<br>        type: String,<br>        required: false<br>    }<br>})<br><br>const form = useForm({<br>    email: &#39;&#39;,<br>    password: &#39;&#39;,<br>    remember: false,<br>})<br><br>const submit = () =&gt; {<br>    form.post(route(&#39;login&#39;), {<br>        onFinish: () =&gt; form.reset(&#39;password&#39;),<br>    })<br>}<br>&lt;/script&gt;</pre><h3>Step 7: Clean Up and Final Steps</h3><h3>Remove TypeScript Files</h3><p>Clean up your project by removing TypeScript-specific files:</p><pre># Remove TypeScript configuration<br>rm tsconfig.json<br>rm tsconfig.node.json<br><br># Remove the main TypeScript file<br>rm resources/js/app.ts<br><br># Remove types directory<br>rm -rf resources/js/types/<br><br># Remove any other .ts files<br>find resources/js -name &quot;*.ts&quot; -not -path &quot;*.vue&quot; -type f -delete</pre><h3>Install and Test</h3><p>Install your dependencies and test everything:</p><pre>npm install<br>npm run build<br>npm run dev</pre><p>Start your Laravel development server:</p><pre>php artisan serve</pre><h3>Common Issues and Solutions</h3><h3>Issue: Build Errors After Conversion</h3><p><strong>Problem</strong>: Vite fails to build with TypeScript-related errors.</p><p><strong>Solution</strong>: Double-check that all .ts files are converted to .js and all TypeScript dependencies are removed from package.json.</p><h3>Issue: Vue Component Props Not Working</h3><p><strong>Problem</strong>: Components show prop validation warnings.</p><p><strong>Solution</strong>: Make sure you’ve converted all defineProps&lt;Interface&gt;() to proper Vue prop definitions with type validation.</p><h3>Issue: Inertia Forms Not Working</h3><p><strong>Problem</strong>: Form submissions fail after conversion.</p><p><strong>Solution</strong>: Remove generic types from useForm&lt;Type&gt;() calls — use plain useForm() instead.</p><h3>Performance Considerations</h3><p>Converting to JavaScript can actually improve your development experience:</p><ul><li><strong>Faster builds</strong>: No TypeScript compilation overhead</li><li><strong>Simpler debugging</strong>: Standard JavaScript debugging tools work perfectly</li><li><strong>Quicker hot reload</strong>: Less processing during development</li><li><strong>Smaller bundle</strong>: No TypeScript compilation artifacts</li></ul><h3>Should You Make This Switch?</h3><p>The decision depends on your team and project:</p><p><strong>Consider JavaScript if:</strong></p><ul><li>Your team is more comfortable with JavaScript</li><li>You’re building a smaller to medium-sized application</li><li>You want faster development iteration</li><li>TypeScript feels like overkill for your use case</li></ul><p><strong>Stick with TypeScript if:</strong></p><ul><li>You’re building a large, complex application</li><li>Your team values type safety and IDE support</li><li>You’re working with multiple developers</li><li>You plan to scale significantly</li></ul><h3>Conclusion</h3><p>Converting Laravel 12’s Vue 3 starter kit from TypeScript to JavaScript is straightforward and gives you all the modern features without the complexity of type annotations. The process mainly involves:</p><ol><li>Removing lang=&quot;ts&quot; from Vue components</li><li>Converting interfaces to Vue prop definitions</li><li>Updating configuration files</li><li>Cleaning up TypeScript dependencies</li></ol><p>You’ll end up with a clean, modern Vue 3 application that’s easier to understand and maintain for JavaScript-focused teams.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96310e921110" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>