<?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 Houdaifa Boucenna on Medium]]></title>
        <description><![CDATA[Stories by Houdaifa Boucenna on Medium]]></description>
        <link>https://medium.com/@houdaifaboucenna?source=rss-bf318e996aa3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YbExeLqaILtlG754KAjrow.jpeg</url>
            <title>Stories by Houdaifa Boucenna on Medium</title>
            <link>https://medium.com/@houdaifaboucenna?source=rss-bf318e996aa3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:27:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@houdaifaboucenna/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Laravel, Inertia.js & Vue 3: The Ultimate Guide to Forms and File Uploads]]></title>
            <link>https://medium.com/@houdaifaboucenna/laravel-inertia-js-vue-3-the-ultimate-guide-to-forms-and-file-uploads-7fb089c01517?source=rss-bf318e996aa3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fb089c01517</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[inertia]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[file-upload]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Houdaifa Boucenna]]></dc:creator>
            <pubDate>Thu, 16 Apr 2026 21:14:10 GMT</pubDate>
            <atom:updated>2026-04-16T21:14:10.951Z</atom:updated>
            <content:encoded><![CDATA[<h3>Laravel + Inertia + Vue 3: Forms, Validation &amp; File Uploads Done Right</h3><p>If you’ve ever built a form in a Vue SPA that talks to a Laravel backend, you know how it goes:</p><pre>const form = reactive({<br>    name: &#39;&#39;,<br>    email: &#39;&#39;,<br>    avatar: null,<br>})<br><br>const errors = ref({})<br>const loading = ref(false)<br><br>async function submit() {<br>    loading.value = true<br>    errors.value = {}<br>    try {<br>        await axios.post(&#39;/api/users&#39;, form)<br>    } catch (e) {<br>        errors.value = e.response.data.errors<br>    } finally {<br>        loading.value = false<br>    }<br>}</pre><p>And that’s just the basics. Add file uploads, progress tracking, form resetting, dirty state — and suddenly you’re maintaining a small library just to handle a form.</p><p>Inertia’s useForm() replaces all of that. No axios, no manual error mapping, no loading flags — it&#39;s all built in, and it talks to your Laravel backend directly.</p><p>In this article, we’ll build a real user profile form from scratch — with text fields, server-side validation, a file upload with a progress bar, and all the edge cases you’ll actually hit in production.</p><p>Let’s get into it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GnB6UxAx3JzvTbZcJc9awA.png" /></figure><h3>Part 1 — Quick Setup</h3><p>If you’re starting fresh, scaffold a new Laravel project with Inertia and Vue 3 already wired:</p><pre>laravel new my-app --using=laravel/vue-starter-kit<br>cd my-app<br>npm install</pre><p>That’s it — Laravel, Inertia, and Vue 3 are all configured out of the box. Run both servers:</p><pre>php artisan serve        # Laravel on :8000<br>npm run dev              # Vite on :5173</pre><p>Head to http://localhost:8000 — you should see the default auth scaffolding already working. Inertia is running.</p><blockquote><em>💡 </em><strong><em>Already have a project?</em></strong><em> If you’re adding Inertia to an existing Laravel app, check the </em><a href="https://inertiajs.com/server-side-setup"><em>official installation guide</em></a><em> — it takes about 10 minutes. Come back once you have a Vue page rendering and we’ll take it from there.</em></blockquote><p>We’ll build everything around a <strong>User Profile</strong> feature — update your name, email, and avatar. Simple enough to follow, real enough to actually learn from.</p><p>Let’s create the route and controller first:</p><pre>php artisan make:controller ProfileController</pre><pre>// routes/web.php<br>Route::middleware(&#39;auth&#39;)-&gt;group(function () {<br>    Route::get(&#39;/profile&#39;, [ProfileController::class, &#39;edit&#39;])-&gt;name(&#39;profile.edit&#39;);<br>    Route::post(&#39;/profile&#39;, [ProfileController::class, &#39;update&#39;])-&gt;name(&#39;profile.update&#39;);<br>});</pre><pre>// app/Http/Controllers/ProfileController.php<br>public function edit(): Response<br>{<br>    return Inertia::render(&#39;Profile/Edit&#39;, [<br>        &#39;user&#39; =&gt; auth()-&gt;user()-&gt;only(&#39;name&#39;, &#39;email&#39;, &#39;avatar&#39;)<br>    ]);<br>}</pre><p>Notice we’re returning Inertia::render() instead of view() — that&#39;s the only difference from a regular Laravel controller. Everything else stays the same. Create the Vue component:</p><pre>mkdir resources/js/Pages/Profile<br>touch resources/js/Pages/Profile/Edit.vue</pre><pre>&lt;script setup&gt;<br>const props = defineProps({<br>    user: Object<br>})<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>    &lt;div&gt;<br>        &lt;h1&gt;Edit Profile&lt;/h1&gt;<br>        &lt;pre&gt;{{ user }}&lt;/pre&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;</pre><p>Visit /profile — you should see your user data on screen. That&#39;s Inertia working — Laravel passed the data, Vue received it as props. No API endpoint, no fetch call.</p><p>Now let’s actually build something with it.</p><h3>Part 2 — Understanding useForm() — What It Actually Does</h3><p>Before we write the actual form, let’s spend two minutes on the mental model — it’ll make everything that follows click immediately.</p><p>When you use axios manually, you’re responsible for four things:</p><ul><li>Holding the form data</li><li>Tracking the loading state</li><li>Catching and mapping errors</li><li>Resetting the form after success</li></ul><p>You write that yourself, every single time. useForm() owns all four of those — you just hand it your initial data and it gives you everything back:</p><pre>import { useForm } from &#39;@inertiajs/vue3&#39;<br>const form = useForm({<br>    name: &#39;John&#39;,<br>    email: &#39;john@example.com&#39;,<br>    avatar: null,<br>})<br><br>// That one line gives you:<br>form.name, form.email  // actual field values<br>form.errors.name       // server-side validation error for that field<br>form.processing        // true while the request is in flight<br>form.progress          // upload progress (0–100), only for file uploads<br>form.isDirty           // true if the user changed anything<br>form.wasSuccessful     // true after a successful submission</pre><p>And these methods you’ll use constantly:</p><pre>form.post(route(&#39;profile.update&#39;))    // submits the form<br>form.reset()                          // resets all fields to initial values<br>form.clearErrors()                    // clears validation errors manually</pre><p>That’s the whole API. No reducers, no stores, no custom composables — just useForm() and you&#39;re done.</p><blockquote><em>💡 </em><strong><em>How does it talk to Laravel?</em></strong><em> Under the hood, </em><em>useForm() uses Inertia&#39;s router to make the request — not axios, not fetch. This means Laravel sees it as a normal form submission, your </em><strong><em>FormRequest validation works as-is</em></strong><em>, and errors come back automatically mapped to the right fields. Zero extra wiring needed.</em></blockquote><p>Here’s the full picture of what happens on a form submit:</p><pre>If User clicks Submit:<br>    → form.processing = true<br>    → Inertia sends POST to Laravel<br>    → Laravel runs FormRequest validation<br><br>If validation fails:<br>    → Laravel redirects back with errors<br>    → Inertia catches them automatically<br>    → form.errors.* populated per field<br>    → form.processing = false<br><br>If validation passes:<br>    → Controller runs, does the work<br>    → Laravel redirects to next page (or back)<br>    → form.wasSuccessful = true<br>    → form.processing = false</pre><p>The key insight is that <strong>you never handle errors manually</strong>. Laravel sends them, Inertia maps them, useForm() exposes them — all automatically. Your Vue component just reads form.errors.name and displays it.</p><p>That’s the shift. Now let’s build it.</p><h3>Part 3 — Your First Form: Create &amp; Validate</h3><p>Let’s build the profile form step by step — Vue component first, then the Laravel side.</p><h4>The Vue Component</h4><pre>&lt;!-- resources/js/Pages/Profile/Edit.vue --&gt;<br>&lt;script setup&gt;<br>import { useForm } from &#39;@inertiajs/vue3&#39;<br>const props = defineProps({<br>    user: Object<br>})<br>const form = useForm({<br>    name: props.user.name,<br>    email: props.user.email,<br>})<br>function submit() {<br>    form.post(route(&#39;profile.update&#39;))<br>}<br>&lt;/script&gt;<br>&lt;template&gt;<br>    &lt;form @submit.prevent=&quot;submit&quot;&gt;<br>        &lt;!-- Name field --&gt;<br>        &lt;div&gt;<br>            &lt;label&gt;Name&lt;/label&gt;<br>            &lt;input v-model=&quot;form.name&quot; type=&quot;text&quot; /&gt;<br>            &lt;span v-if=&quot;form.errors.name&quot;&gt;{{ form.errors.name }}&lt;/span&gt;<br>        &lt;/div&gt;<br>        &lt;!-- Email field --&gt;<br>        &lt;div&gt;<br>            &lt;label&gt;Email&lt;/label&gt;<br>            &lt;input v-model=&quot;form.email&quot; type=&quot;email&quot; /&gt;<br>            &lt;span v-if=&quot;form.errors.email&quot;&gt;{{ form.errors.email }}&lt;/span&gt;<br>        &lt;/div&gt;<br>        &lt;!-- Submit button --&gt;<br>        &lt;button type=&quot;submit&quot; :disabled=&quot;form.processing&quot;&gt;<br>            {{ form.processing ? &#39;Saving...&#39; : &#39;Save Changes&#39; }}<br>        &lt;/button&gt;<br>    &lt;/form&gt;<br>&lt;/template&gt;<br></pre><p>Three things to notice here:</p><ul><li><strong>v-model=&quot;form.name&quot;</strong> — binds the input directly to useForm() state, no extra ref() needed</li><li><strong>form.errors.name</strong> — server-side validation errors show up here automatically, no mapping code</li><li><strong>:disabled=&quot;form.processing&quot;</strong> — button disables itself while the request is in flight, preventing double submissions for free</li></ul><h4>The Laravel Side</h4><p>Create the FormRequest:</p><pre>php artisan make:request UpdateProfileRequest</pre><pre>// app/Http/Requests/UpdateProfileRequest.php<br>public function rules(): array<br>{<br>    return [<br>        &#39;name&#39;  =&gt; [&#39;required&#39;, &#39;string&#39;, &#39;max:255&#39;],<br>        &#39;email&#39; =&gt; [&#39;required&#39;, &#39;email&#39;, &#39;unique:users,email,&#39; . auth()-&gt;id()],<br>    ];<br>}</pre><p>Update the controller:</p><pre>// app/Http/Controllers/ProfileController.php<br>public function update(UpdateProfileRequest $request): RedirectResponse<br>{<br>    auth()-&gt;user()-&gt;update($request-&gt;validated());<br>    return back()-&gt;with(&#39;success&#39;, &#39;Profile updated successfully.&#39;);<br>}</pre><p>That’s it — no $request-&gt;validate(), no manual error returning, no JSON responses. Laravel handles validation, Inertia handles the error transport, useForm() handles the display. The whole chain just works.</p><h4>See It In Action</h4><p>Try submitting the form with an empty name — you’ll see the error appear under the field instantly, without a page reload. Fix it and submit again — the error clears automatically.</p><p>That’s the magic. <strong>Same server-side validation you’ve always written in Laravel, surfacing in Vue with zero extra code.</strong></p><blockquote><em>💡 </em><strong><em>Flash messages</em></strong><em> Notice we returned </em><em>back()-&gt;with(&#39;success&#39;, &#39;...&#39;). To display that in Vue, you need to pass flash messages through Inertia&#39;s shared data via </em><em>HandleInertiaRequests middleware. Worth setting up now if you haven&#39;t — your success toast will need it.</em></blockquote><pre>// app/Http/Middleware/HandleInertiaRequests.php <br>public function share(Request $request): array <br>{ <br>    return [         <br>        ...parent::share($request), <br>        &#39;flash&#39; =&gt; [ <br>            &#39;success&#39; =&gt; session(&#39;success&#39;), <br>            &#39;error&#39;   =&gt; session(&#39;error&#39;),         <br>        ],     <br>    ]; <br>}<br></pre><p>Then in any Vue component: usePage().props.flash.success</p><h3>Part 4 — Editing &amp; Resetting Forms</h3><p>Part 3 covered creating. Now let’s talk about editing — which sounds simple but has a few gotchas that catch most people off guard when working with Inertia for the first time.</p><h4>Pre-filling the Form With Existing Data</h4><p>We already did this partially in Part 3 — we passed user as a prop from the controller and initialized useForm() with it:</p><pre>const form = useForm({<br>    name: props.user.name,<br>    email: props.user.email,<br>})</pre><p>This is the correct way to pre-fill a form in Inertia. Don’t fetch the data from an API endpoint inside onMounted() — you already have it as a prop. Laravel sent it, Inertia delivered it, Vue received it. Use it directly.</p><h4>Tracking Dirty State — Warn Before Navigating Away</h4><p>form.isDirty is true the moment the user changes anything from the original values. This is useful for one very common UX pattern — warning the user before they navigate away with unsaved changes.</p><p>Inertia gives you a hook for exactly this:</p><pre>import { useForm } from &#39;@inertiajs/vue3&#39;<br>import { onBeforeMount } from &#39;vue&#39;<br>import { router } from &#39;@inertiajs/vue3&#39;<br><br>const form = useForm({<br>    name: props.user.name,<br>    email: props.user.email,<br>})<br>// Warn before navigating away with unsaved changes<br>router.on(&#39;before&#39;, (event) =&gt; {<br>    if (form.isDirty) {<br>        if (!confirm(&#39;You have unsaved changes. Are you sure you want to leave?&#39;)) {<br>            event.preventDefault()<br>        }<br>    }<br>})</pre><p>Clean, no extra libraries, works with Inertia’s own router — so it catches navigation triggered by &lt;Link&gt; components and router.visit() calls, not just browser back buttons.</p><h4>Resetting the Form</h4><p>Two scenarios here — resetting after a successful save, and letting the user cancel their edits manually.</p><p><strong>After a successful save</strong>, use the onSuccess callback:</p><pre>function submit() {<br>    form.post(route(&#39;profile.update&#39;), {<br>        onSuccess: () =&gt; form.reset()<br>    })<br>}</pre><p><strong>For a cancel button</strong>, reset to the original prop values:</p><pre>function cancel() {<br>    form.reset()<br>    form.clearErrors()<br>}</pre><p>form.reset() resets all fields back to the values you passed into useForm() when you initialized it — not to empty strings, but to the original data. So if the user loaded the form with name: &#39;John&#39;, <strong>hitting cancel brings it back to </strong>&#39;John&#39;<strong>, not </strong>&#39;&#39;<strong>.</strong></p><p>form.clearErrors() wipes any validation errors that might be showing — always pair these two together on cancel.</p><h4>Putting It All Together</h4><p>Here’s the full updated component with pre-fill, dirty state warning, reset, and cancel:</p><pre>&lt;script setup&gt;<br>import { useForm, router } from &#39;@inertiajs/vue3&#39;<br>const props = defineProps({<br>    user: Object<br>})<br>const form = useForm({<br>    name: props.user.name,<br>    email: props.user.email,<br>})<br>router.on(&#39;before&#39;, (event) =&gt; {<br>    if (form.isDirty) {<br>        if (!confirm(&#39;You have unsaved changes. Are you sure you want to leave?&#39;)) {<br>            event.preventDefault()<br>        }<br>    }<br>})<br>function submit() {<br>    form.post(route(&#39;profile.update&#39;), {<br>        onSuccess: () =&gt; form.reset()<br>    })<br>}<br>function cancel() {<br>    form.reset()<br>    form.clearErrors()<br>}<br>&lt;/script&gt;<br>&lt;template&gt;<br>    &lt;form @submit.prevent=&quot;submit&quot;&gt;<br>        &lt;div&gt;<br>            &lt;label&gt;Name&lt;/label&gt;<br>            &lt;input v-model=&quot;form.name&quot; type=&quot;text&quot; /&gt;<br>            &lt;span v-if=&quot;form.errors.name&quot;&gt;{{ form.errors.name }}&lt;/span&gt;<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>            &lt;label&gt;Email&lt;/label&gt;<br>            &lt;input v-model=&quot;form.email&quot; type=&quot;email&quot; /&gt;<br>            &lt;span v-if=&quot;form.errors.email&quot;&gt;{{ form.errors.email }}&lt;/span&gt;<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>            &lt;!-- Save button - disabled when nothing changed or request in flight --&gt;<br>            &lt;button<br>                type=&quot;submit&quot;<br>                :disabled=&quot;form.processing || !form.isDirty&quot;<br>            &gt;<br>                {{ form.processing ? &#39;Saving...&#39; : &#39;Save Changes&#39; }}<br>            &lt;/button&gt;<br>            &lt;!-- Cancel button - only visible when something changed --&gt;<br>            &lt;button<br>                v-if=&quot;form.isDirty&quot;<br>                type=&quot;button&quot;<br>                @click=&quot;cancel&quot;<br>            &gt;<br>                Cancel<br>            &lt;/button&gt;<br>        &lt;/div&gt;<br>    &lt;/form&gt;<br>&lt;/template&gt;</pre><p>Two small details worth pointing out:</p><ul><li><strong>:disabled=&quot;form.processing || !form.isDirty&quot;</strong> — the save button is disabled if nothing has changed. No point submitting an unchanged form.</li><li><strong>v-if=&quot;form.isDirty&quot;</strong> on the cancel button — it only appears when there&#39;s actually something to cancel. Cleaner UX, zero extra state.</li></ul><blockquote><em>💡 </em><strong><em>Partial updates with </em></strong><strong><em>form.patch()</em></strong><em> If you&#39;re updating a resource and don&#39;t want to send the entire form payload, use </em><em>form.patch() instead of </em><em>form.post() — it sends a </em><em>PATCH request, semantically correct for partial updates. Wire it to a </em><em>Route::patch() on the Laravel side and everything works the same way.</em></blockquote><h3>Part 5 — File Uploads With Progress</h3><p>This is where most tutorials drop the ball — they show you how to attach a file to a form but skip the progress tracking, the validation errors, and what happens when something goes wrong. We’ll cover all of it.</p><h4>Add the Avatar Field to the Form</h4><p>First, add avatar to your existing useForm():</p><pre>const form = useForm({<br>    name: props.user.name,<br>    email: props.user.email,<br>    avatar: null,        // add this<br>})</pre><h4>Handle the File Input</h4><p>File inputs can’t use v-model — bind them manually with @change instead:</p><pre>&lt;div&gt;<br>    &lt;label&gt;Avatar&lt;/label&gt;<br>    &lt;input<br>        type=&quot;file&quot;<br>        accept=&quot;image/*&quot;<br>        @change=&quot;form.avatar = $event.target.files[0]&quot;<br>    /&gt;<br>    &lt;span v-if=&quot;form.errors.avatar&quot;&gt;{{ form.errors.avatar }}&lt;/span&gt;<br>&lt;/div&gt;</pre><h4>Tell Inertia to Send as Multipart</h4><p>When your form includes a file, add forceFormData: true to the submit call — this tells Inertia to send the request as multipart/form-data instead of JSON:</p><pre>function submit() {<br>    form.post(route(&#39;profile.update&#39;), {<br>        forceFormData: true,<br>        onSuccess: () =&gt; form.reset()<br>    })<br>}</pre><h4>Show a Progress Bar</h4><p>form.progress is automatically populated during file uploads — it gives you a percentage value from 0 to 100. Add this right below your file input:</p><pre>&lt;div v-if=&quot;form.progress&quot;&gt;<br>    &lt;progress :value=&quot;form.progress.percentage&quot; max=&quot;100&quot;&gt;<br>        {{ form.progress.percentage }}%<br>    &lt;/progress&gt;<br>    &lt;span&gt;{{ form.progress.percentage }}%&lt;/span&gt;<br>&lt;/div&gt;</pre><p>It shows up automatically when the upload starts and disappears when it’s done. No manual event listeners, no axios upload progress hacks.</p><h4>Validate on the Laravel Side</h4><p>Update your UpdateProfileRequest:</p><pre>public function rules(): array<br>{<br>    return [<br>        &#39;name&#39;   =&gt; [&#39;required&#39;, &#39;string&#39;, &#39;max:255&#39;],<br>        &#39;email&#39;  =&gt; [&#39;required&#39;, &#39;email&#39;, &#39;unique:users,email,&#39; . auth()-&gt;id()],<br>        &#39;avatar&#39; =&gt; [&#39;nullable&#39;, &#39;image&#39;, &#39;mimes:jpg,jpeg,png,webp&#39;, &#39;max:2048&#39;],<br>    ];<br>}</pre><h3>Part 6 — Conclusion</h3><p>Let’s look at where we started — a Vue form manually juggling axios calls, error mapping, loading flags, and upload progress events. All boilerplate, all written from scratch, every single time.</p><p>Here’s what that same form looks like now:</p><pre>const form = useForm({<br>    name: props.user.name,<br>    email: props.user.email,<br>    avatar: null,<br>})<br><br>function submit() {<br>    form.post(route(&#39;profile.update&#39;), {<br>        forceFormData: true,<br>        onSuccess: () =&gt; form.reset()<br>    })<br>}</pre><p>That’s it. Server-side validation errors surface automatically. The submit button disables itself. Upload progress tracks itself. Dirty state tracks itself. Laravel stays Laravel — FormRequests, controllers, redirects, all unchanged.</p><p>To recap what we covered:</p><ul><li>Why manual axios form handling creates unnecessary boilerplate</li><li>What useForm() gives you out of the box and how it talks to Laravel</li><li>Building a real form with server-side validation and automatic error display</li><li>Pre-filling edit forms the right way, dirty state tracking, reset and cancel</li><li>File uploads with a real progress bar and proper server-side validation</li><li>All the edge cases — old file cleanup, server limits, input reset after success</li></ul><p>useForm() isn&#39;t just a convenience — it&#39;s the right mental model for forms in an Inertia app. Once it clicks, you&#39;ll never want to go back to managing form state manually.</p><h3>🔗 Stay Connected</h3><p>Follow me for more Laravel tutorials, dev tips, deployment workflows and<br>solving real-world production headaches.</p><p><em>➣ Follow me on </em><a href="https://www.linkedin.com/in/houdaifaboucenna/"><strong><em>LinkedIn</em></strong></a><strong><em><br></em></strong><em>➣</em> <em>Follow me </em>here on <a href="https://medium.com/@houdaifaboucenna"><strong><em>Medium</em></strong></a> and <a href="https://medium.com/@houdaifaboucenna/subscribe"><strong><em>join my mailing list</em></strong></a> for more in-depth content and tutorials!<br><em>➣ Follow me on </em><a href="https://dev.to/houdaifa360"><strong><em>D</em>ev.to</strong></a></p><p><strong>Found this article useful?</strong><br>🙏 Show your support by clapping 👏, subscribing 🔔, sharing to social networks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fb089c01517" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Slow Requests to Scalable Background Jobs with Laravel Queues & Horizon]]></title>
            <link>https://medium.com/@houdaifaboucenna/from-slow-requests-to-scalable-background-jobs-with-laravel-queues-horizon-b4ba53e62b6d?source=rss-bf318e996aa3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4ba53e62b6d</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[horizons]]></category>
            <category><![CDATA[queue]]></category>
            <dc:creator><![CDATA[Houdaifa Boucenna]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 13:39:05 GMT</pubDate>
            <atom:updated>2026-04-10T13:39:05.173Z</atom:updated>
            <content:encoded><![CDATA[<p>Almost anyone <strong>has</strong> experienced a scenario where <strong>you click</strong> a “Register / Submit” button, then <strong>stare</strong> at the screen waiting seconds — if not minutes — for a response, only to see a success message <strong>or</strong>, even worse, some errors popping up.</p><p>I know, it feels frustrating. It gives a bad user experience, and honestly? Everyone will just go find another faster solution.</p><p>In this article, we’ll explain what’s actually happening <strong>behind</strong> that loading spinner — and how you can better architect your solution to fix this once and for all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x8P482qzettdk9EYumRwfw.png" /></figure><h3>Part 1 — The Problem (The Real One)</h3><p>Let’s make it concrete. Here’s what a typical registration endpoint looks like in most Laravel apps:</p><pre>public function register(Request $request)<br>{<br>    $user = User::create($request-&gt;validated());<br><br>    // Send welcome email<br>    Mail::to($user-&gt;email)-&gt;send(new WelcomeEmail($user));<br><br>    // Generate and store a welcome PDF<br>    $pdf = Pdf::loadView(&#39;pdfs.welcome&#39;, compact(&#39;user&#39;));<br>    Storage::put(&quot;welcome/{$user-&gt;id}.pdf&quot;, $pdf-&gt;output());<br><br>    return response()-&gt;json([&#39;message&#39; =&gt; &#39;Registration successful!&#39;]);<br>}</pre><p>Looks familiar, right?</p><p>The problem is that everything here runs <strong>sequentially</strong>, inside the same request. <strong>Laravel won’t return that success response until every single line finishes executing — the email, the Slack call, the PDF, all of it.</strong></p><p>So if your mail provider takes 2 seconds and the PDF takes another second, your user just waited 3<strong>+ seconds</strong> to see “Registration successful”. And that’s on a good day, with no timeouts or failures.</p><p>This pattern shows up everywhere:</p><ul><li>Sending emails or SMS after an action</li><li>Calling third-party APIs (payment gateways, webhooks, analytics)</li><li>Generating reports or exports</li><li>Processing uploaded files or images</li></ul><p>All of these have one thing in common — <strong>the user doesn’t need to wait for them</strong>. They just need to know their action was received. The rest can happen in the background.</p><p>That’s exactly what we’re going to fix.</p><h3><strong>Part 2 — How Laravel Queues Work</strong></h3><p>Before jumping into code, let’s build a quick mental model — I promise this is the only “theory” section.</p><p>When a user hits your endpoint, Laravel normally does everything <strong>in that same request lifecycle</strong> — sends the email, calls the API, generates the PDF — and only then returns a response. The user waits for all of it.</p><p>Queues flip that completely.</p><p>Instead of doing the heavy work immediately, you <strong>push a job onto a queue</strong> — think of it as a to-do list — and return the response right away. A separate process called a <strong>worker</strong> is running in the background, picking jobs off that list and executing them one by one, completely outside the user’s request.</p><p>Here’s the full picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ASNNvNGkDYr4KLocXZ5iGg.png" /></figure><p>Three actors to keep in mind:</p><ul><li><strong>Job</strong> — the class that contains the actual work (SendWelcomeEmail, GenerateInvoice...)</li><li><strong>Queue</strong> — the list where jobs wait (we’ll use Redis, more on that in a second)</li><li><strong>Worker</strong> — the background process that pulls jobs from the queue and runs them (php artisan queue:work)</li></ul><p>That’s really it. The rest is just configuration and knowing which scenarios to apply this to — which is exactly what we’ll cover next.</p><blockquote>💡 <strong>Why Redis and not the database driver?</strong> Laravel supports multiple queue drivers — database, Redis, SQS, and others. The database driver works fine for getting started, but Redis is faster and lighter on your DB, and it’s what you’ll realistically use in production. So we’ll go with Redis from the start and skip the detour.</blockquote><h3>Part 3 — Setting Up Redis &amp; Queue Config</h3><p>Alright, enough theory — let’s get our hands dirty.</p><h4><strong>Install Redis On Ubuntu / your VPS:</strong></h4><pre>sudo apt update<br>sudo apt install redis-server -y<br>sudo systemctl enable redis-server<br>sudo systemctl start redis-server<br><br>redis-cli ping        # If you got PONG — you&#39;re good.</pre><p>Find below the installation instructions for each platform:<br><a href="https://redis.io/docs/latest/operate/oss_and_stack/install/archive/install-redis/">https://redis.io/docs/latest/operate/oss_and_stack/install/archive/install-redis/</a></p><h4>Install the Laravel Redis Package</h4><p>Laravel needs one extra package to talk to Redis:</p><pre>composer require predis/predis</pre><h4>Configure Your .env</h4><p>Two changes only in <em>.</em>env</p><pre>QUEUE_CONNECTION=redis           # switch to the redis driver<br><br>REDIS_CLIENT=predis              # use the predis package installed<br>REDIS_HOST=127.0.0.1<br>REDIS_PASSWORD=null<br>REDIS_PORT=6379</pre><p>By default, Laravel uses sync as the queue driver — meaning jobs run immediately, synchronously, defeating the whole purpose. Switching to redis is what actually enables the background behavior.</p><h4>Quick Sanity Check</h4><p>Before writing a single job, let’s confirm everything is wired correctly. Run your worker:</p><p>bash</p><pre>php artisan queue:work</pre><p>You should see something like:</p><pre>INFO  Processing jobs from the [default] queue.</pre><p>No errors? Perfect. Leave that terminal open — that’s your worker listening for jobs. Open a second terminal for the next steps.</p><blockquote>💡 <strong>Heads up for production</strong> Running queue:work manually is fine for local development, but on your server you need a process manager to keep it alive — if it crashes, your jobs just pile up with nobody processing them. We&#39;ll cover that with <strong>Supervisor</strong> in the Horizon section.</blockquote><h3>Part 4 — Your First Real Job</h3><p>Remember that messy controller from Part 1? Let’s start fixing it — one job at a time.</p><p>We’ll tackle the welcome email first since it’s the most common and the cleanest example to learn the pattern with.</p><pre>php artisan make:job SendWelcomeEmail        # Create the Job</pre><p>This creates app/Jobs/SendWelcomeEmail.php. Open it up:</p><pre>class SendWelcomeEmail implements ShouldQueue<br>{<br>    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;<br><br>    public function __construct(public User $user) {}<br><br>    public function handle(): void<br>    {<br>        Mail::to($this-&gt;user-&gt;email)-&gt;send(new WelcomeEmail($this-&gt;user));<br>    }<br>}</pre><p>Two things to notice here:</p><ul><li><strong>ShouldQueue</strong> — This interface is what tells Laravel &quot;don&#39;t run this now, push it to the queue.&quot;</li><li><strong>SerializesModels</strong> — handles serializing and deserializing your Eloquent models automatically so that you can pass $user directly without worrying about it</li></ul><h4>Dispatch It From Your Controller</h4><p>Now go back to your controller and replace the Mail::to(...) line:</p><pre>// Before<br>Mail::to($user-&gt;email)-&gt;send(new WelcomeEmail($user));<br><br>// After<br>SendWelcomeEmail::dispatch($user);</pre><p>That’s it—one line. Your controller doesn’t care when or how the email gets sent anymore — it just says “handle this” and moves on.</p><p>Your registration endpoint now looks like this:</p><pre>public function register(Request $request)<br>{<br>    $user = User::create($request-&gt;validated());<br>    SendWelcomeEmail::dispatch($user);<br>    return response()-&gt;json([&#39;message&#39; =&gt; &#39;Registration successful!&#39;]);<br>}</pre><p>The response comes back <strong>instantly</strong>. The email is sent in the background by your worker.</p><blockquote><em>💡 </em><strong><em>Want to delay a job?</em></strong><em> You can dispatch a job with a delay super easily:</em></blockquote><blockquote><em>SendWelcomeEmail::dispatch($user)-&gt;delay(now()-&gt;addMinutes(5));</em></blockquote><blockquote><em>Useful for things like “send a follow-up email 10 minutes after registration”.</em></blockquote><p>That’s the core pattern — everything else you’ll do with queues is just a variation of this. Create a job, move the logic intohandle() and dispatch it. Let&#39;s now apply this to three real-world scenarios you&#39;ll actually run into.</p><h3>Part 5 — Real World Scenarios</h3><h4>Scenario A — Calling a Third-Party API (Slack, SMS, Webhooks)</h4><p>Third-party APIs are the #1 culprit for slow responses. You have zero control over their response time — and they can fail.</p><pre>php artisan make:job NotifyAdminOnSlack   # create the job</pre><pre>class NotifyAdminOnSlack implements ShouldQueue<br>{<br>    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;<br>    <br>    public int $tries = 3;<br>    public int $backoff = 10;<br>    <br>    public function __construct(public User $user) {}<br>    <br>    public function handle(): void<br>    {<br>        Http::post(config(&#39;services.slack.webhook&#39;), [<br>            &#39;text&#39; =&gt; &quot;New user registered: {$this-&gt;user-&gt;email}&quot;<br>        ]);<br>    }<br>}</pre><p>Notice $tries = 3 and $backoff = 10 — <strong>If Slack is down or slow</strong>, Laravel will automatically retry the job 3 times, waiting 10 seconds between each attempt. Your user never sees any of this.</p><p>Dispatch both jobs from your controller:</p><pre>SendWelcomeEmail::dispatch($user);<br>NotifyAdminOnSlack::dispatch($user);<br>return response()-&gt;json([&#39;message&#39; =&gt; &#39;Registration successful!&#39;]);</pre><p>Two background jobs, zero waiting.</p><h4>Scenario B — Generating a PDF or Report on Demand</h4><p>This one is slightly different — the user actually needs the result, they just don’t need to wait for it <strong>right now</strong>.</p><pre>php artisan make:job GenerateWelcomePdf       # create the job</pre><pre>class GenerateWelcomePdf implements ShouldQueue<br>{<br>    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;<br>    <br>    public function __construct(public User $user) {}<br>    <br>    public function handle(): void<br>    {<br>        $pdf = Pdf::loadView(&#39;pdfs.welcome&#39;, [<br>            &#39;user&#39; =&gt; $this-&gt;user<br>        ]);<br>        Storage::put(<br>            &quot;welcome/{$this-&gt;user-&gt;id}.pdf&quot;,<br>            $pdf-&gt;output()<br>        );<br>        // Notify the user it&#39;s ready<br>        $this-&gt;user-&gt;notify(new PdfReadyNotification());<br>    }<br>}</pre><p>The pattern here is: generate → store → notify. The user gets an instant response on registration, and a notification (email, in-app, whatever you prefer) once their PDF is actually ready. Clean and professional.</p><h4>Scenario C — Processing a Bulk CSV Import</h4><p>This is where queues really shine. Importing 5,000 rows in a single request is a recipe for timeouts and misery.</p><p>Instead of one giant job, <strong>chunk your data into smaller jobs</strong>:</p><pre>php artisan make:job ImportUserRow            # create the job</pre><pre>class ImportUserRow implements ShouldQueue<br>{<br>    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;<br>    <br>    public function __construct(public array $row) {}<br>    <br>    public function handle(): void<br>    {<br>        User::updateOrCreate(<br>            [&#39;email&#39; =&gt; $this-&gt;row[&#39;email&#39;]],<br>            [<br>                &#39;name&#39; =&gt; $this-&gt;row[&#39;name&#39;],<br>                &#39;phone&#39; =&gt; $this-&gt;row[&#39;phone&#39;],<br>            ]<br>        );<br>    }<br>}</pre><p>Then, in your import controller, loop through the CSV and dispatch one job per row (or per chunk):</p><pre>public function import(Request $request)<br>{<br>    $rows = array_map(&#39;str_getcsv&#39;, file($request-&gt;file(&#39;csv&#39;)));<br>    foreach ($rows as $row) {<br>        ImportUserRow::dispatch($row);<br>    }<br>    return response()-&gt;json([<br>        &#39;message&#39; =&gt; &#39;Import started! We will notify you when it\&#39;s done.&#39;<br>    ]);<br>}</pre><p>5,000 rows? 50,000 rows? Doesn’t matter — <strong>your endpoint returns in milliseconds,</strong> and your workers chew through the data in the background at their own pace.</p><blockquote><em>💡 </em><strong><em>Need all jobs to finish before doing something?</em></strong><em> Laravel has </em><em>Bus::batch() for exactly this — group jobs together, track their progress, and run a callback when they all complete. Worth a separate deep-dive on its own.</em></blockquote><p>Three scenarios, one pattern. Create the job, handle the work, dispatch and forget. Next up — what happens when things go wrong?</p><h3>Part 6 — Handling Failures Like a Pro</h3><p>Background jobs fail. Mail providers go down, APIs timeout, PDFs throw exceptions — it happens. The difference between a solid implementation and a fragile one is how you handle it when things go wrong.</p><h4>Set Up the Failed Jobs Table</h4><p>First, make sure you have the failed jobs table:</p><pre>php artisan queue:failed-table             # create the migration file<br>php artisan migrate</pre><p>Laravel will now store any failed job in this table instead of silently dropping it — including the exception, the payload, and when it failed.</p><h4>Retries, Timeouts &amp; Backoff</h4><p>You can control failure behavior directly on the job class:</p><pre>class SendWelcomeEmail implements ShouldQueue<br>{<br>    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;<br>    public int $tries = 3;        // retry up to 3 times<br>    public int $timeout = 30;     // kill the job if it runs longer than 30s<br>    public int $backoff = 15;     // wait 15 seconds between retries<br>    // ...<br>}</pre><p>Or if you want <strong>exponential backoff</strong> — waiting longer after each failed attempt:</p><pre>public function backoff(): array<br>{<br>    return [10, 30, 60]; // 10s after 1st fail, 30s after 2nd, 60s after 3rd<br>}</pre><p>This is great for flaky third-party APIs — instead of hammering them every 10 seconds, you give them room to recover.</p><h4>The failed() Method</h4><p>When a job exhausts all its retries, Laravel calls the failed() method on it — if you define one:</p><pre>public function failed(\Throwable $exception): void<br>{<br>    // Notify yourself, log it, alert the user...<br>    Log::error(&quot;SendWelcomeEmail failed for user {$this-&gt;user-&gt;id}&quot;, [<br>        &#39;error&#39; =&gt; $exception-&gt;getMessage()<br>    ]);<br>    $this-&gt;user-&gt;notify(new EmailFailedNotification());<br>}</pre><p>Never leave this empty on jobs that matter. Silently failing jobs are worse than crashing — at least a crash is loud.</p><h4>Managing Failed Jobs via CLI</h4><pre>php artisan queue:failed       # See all failed jobs<br>php artisan queue:retry 5      # Retry a specific failed job by its ID<br>php artisan queue:retry all    # Retry all failed jobs at once<br>php artisan queue:forget 5     # Delete a specific failed job<br>php artisan queue:flush        # Clear the entire failed jobs table</pre><h4>ShouldBeUnique — Prevent Duplicate Jobs</h4><p>Sometimes the same job gets dispatched multiple times — user double-clicks, a webhook fires twice, whatever. For jobs where duplicates are a real problem, implement ShouldBeUnique:</p><pre>class GenerateWelcomePdf implements ShouldQueue, ShouldBeUnique<br>{<br>    public int $uniqueFor = 3600; // lock for 1 hour<br> <br>    public function uniqueId(): string<br>    {<br>        return $this-&gt;user-&gt;id; // one job per user at a time<br>    }<br>}</pre><p>Laravel will skip dispatching if a job with the same uniqueId() is already in the queue. Clean solution, zero extra code on the dispatch side.</p><blockquote><em>💡 </em><strong><em>Golden rule:</em></strong><em> always define </em><em>$tries, </em><em>$timeout, and </em><em>failed() on any job that touches a third-party service or generates critical data. The 2 minutes it takes to add them will save you hours of debugging in production.</em></blockquote><h3>Part 7 — Laravel Horizon</h3><p>queue:work gets the job done locally, but in production, you need visibility — which jobs are running, how long they&#39;re taking, what&#39;s failing, and whether your workers are keeping up. That&#39;s exactly what Horizon gives you.</p><h4>Install Horizon</h4><pre>composer require laravel/horizon<br>php artisan horizon:install            # install and create migration files<br>php artisan migrate</pre><p>This publishes a config file at config/horizon.php and sets up the dashboard.</p><h4>Basic Configuration</h4><p>Open config/horizon.php. The part you care about most is environments:</p><pre>&#39;environments&#39; =&gt; [<br>    &#39;production&#39; =&gt; [<br>        &#39;supervisor-1&#39; =&gt; [<br>            &#39;maxProcesses&#39; =&gt; 10,<br>            &#39;balanceMaxShift&#39; =&gt; 1,<br>            &#39;balanceCooldown&#39; =&gt; 3,<br>        ],<br>    ],<br>    &#39;local&#39; =&gt; [<br>        &#39;supervisor-1&#39; =&gt; [<br>            &#39;maxProcesses&#39; =&gt; 3,<br>        ],<br>    ],<br>],</pre><p>Horizon uses <strong>supervisors</strong> to manage your workers internally — don’t confuse these with the system-level Supervisor we’ll set up in a moment. These are Horizon’s own worker groups.</p><p>You can also assign specific jobs to specific queues and control priority:</p><pre>&#39;supervisor-1&#39; =&gt; [<br>    &#39;connection&#39; =&gt; &#39;redis&#39;,<br>    &#39;queue&#39; =&gt; [&#39;critical&#39;, &#39;default&#39;, &#39;low&#39;],<br>    &#39;balance&#39; =&gt; &#39;auto&#39;,<br>    &#39;maxProcesses&#39; =&gt; 10,<br>],</pre><p>Jobs on the critical queue gets processed beforedefault, which gets processed before low. Useful when you want invoice processing to always beat bulk imports.</p><p>Dispatch to a specific queue like this:</p><pre>GenerateInvoice::dispatch($order)-&gt;onQueue(&#39;critical&#39;);<br>ImportUserRow::dispatch($row)-&gt;onQueue(&#39;low&#39;);</pre><h4>Protect the Dashboard</h4><p>The Horizon dashboard runs at /horizon and exposes sensitive data — failed jobs, job payloads, throughput. Lock it down:</p><pre>// app/Providers/HorizonServiceProvider.php<br>protected function gate(): void<br>{<br>    Gate::define(&#39;viewHorizon&#39;, function ($user) {<br>        return in_array($user-&gt;email, [<br>            &#39;you@yourdomain.com&#39;,<br>        ]);<br>    });<br>}</pre><p>Only whitelisted emails can access the dashboard in production. Simple, effective.</p><h4>Reading the Dashboard</h4><p>Once Horizon is running (php artisan horizon), head to /horizon:</p><ul><li><strong>Throughput</strong> — how many jobs per minute your workers are processing</li><li><strong>Runtime</strong> — average execution time per job class — if something spikes here, that’s your bottleneck</li><li><strong>Wait time</strong> — how long jobs sit in the queue before a worker picks them up — if this grows, you need more workers</li><li><strong>Failed jobs</strong> — everything that broke, with the full exception and payload right there in the UI — no more digging through logs</li></ul><p>This alone is worth installing Horizon for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Xzj79Uyu_GC3xZpolZ-dQ.png" /></figure><h4>Keep Horizon Running with Supervisor</h4><p>On your server, you need Supervisor to keep Horizon alive. If it crashes or the server restarts, Supervisor brings it back automatically.</p><pre>sudo apt install supervisor -y                   # Install Supervisor<br><br>sudo nano /etc/supervisor/conf.d/horizon.conf    # Create a config file</pre><pre># horizon.conf<br>[program:horizon]<br>process_name=%(program_name)s<br>command=php /var/www/yourapp/artisan horizon<br>autostart=true<br>autorestart=true<br>user=www-data<br>redirect_stderr=true<br>stdout_logfile=/var/www/yourapp/storage/logs/horizon.log<br>stopwaitsecs=3600</pre><p>Apply and start:</p><pre>sudo supervisorctl reread                  # reload the config<br>sudo supervisorctl update<br>sudo supervisorctl start horizon</pre><p>One last thing — whenever you deploy new code, restart Horizon gracefully so it picks up the changes without dropping running jobs:</p><pre>php artisan horizon:terminate        # run manually or put in CICD pipeline</pre><h3>Part 8 — Production Checklist</h3><p>Before you ship, run through this quickly:</p><p><strong>Redis</strong></p><ul><li>Redis is installed and running on your server (redis-cli ping returns PONG)</li><li>QUEUE_CONNECTION=redis in your production .env</li><li>Redis password is set if your server is exposed</li></ul><p><strong>Jobs</strong></p><ul><li>Every job that touches a third-party service has $tries, $timeout and backoff() defined</li><li>Critical jobs implement failed() and notify you when they break</li><li>Duplicate-sensitive jobs implement ShouldBeUnique</li><li>Failed jobs table migrated (queue:failed-table)</li></ul><p><strong>Horizon</strong></p><ul><li>Dashboard protected with gate() — not open to the public</li><li>Queue priorities configured (critical, default, low)</li><li>maxProcesses tuned to your server&#39;s capacity</li></ul><p><strong>Supervisor</strong></p><ul><li>Horizon running under Supervisor (supervisorctl status horizon shows RUNNING)</li><li>horizon:terminate added to your deploy script</li><li>Horizon logs are accessible at storage/logs/horizon.log</li></ul><p><strong>Sanity check</strong></p><ul><li>Trigger a job locally and confirm the worker picks it up</li><li>Intentionally fail a job and confirm it shows up in /horizon and queue:failed</li><li>Check wait times in Horizon after your first real traffic — scale workers if needed</li></ul><h3>Part 9 — Conclusion</h3><p>Let’s go back to where we started — a user clicking “Register” and staring at a spinner for 8 seconds.</p><p>With everything we’ve set up, here’s what that same flow looks like now:</p><pre>User clicks Register<br>    → Controller creates the user<br>    → Dispatches 3 jobs to Redis (takes ~2ms)<br>    → Returns &quot;Registration successful&quot; instantly ✓<br><br>Meanwhile, in the background:<br>    → Worker picks up SendWelcomeEmail   → email sent<br>    → Worker picks up NotifyAdminOnSlack → Slack notified  <br>    → Worker picks up GenerateWelcomePdf → PDF stored, user notified</pre><p>The user is already on the dashboard while your workers are still doing the heavy lifting. That’s the difference.</p><h4>To recap what we covered:</h4><ul><li>Why synchronous code kills user experience and where it hides in typical Laravel apps</li><li>How the <strong>queue / job / worker model</strong> works under the hood</li><li>Setting up <strong>Redis</strong> and wiring it to Laravel in minutes</li><li>Converting slow controller logic into clean, dispatchable jobs</li><li>Three real-world scenarios — API calls, PDF generation, bulk imports</li><li>Handling failures properly with retries, backoff, and failed()</li><li>Monitoring everything in production with Laravel Horizon and Supervisor</li></ul><p><strong>Queues</strong> aren’t an advanced topic — they’re a fundamental tool, and once you get comfortable with the pattern, you’ll start seeing opportunities to use them everywhere.</p><h4><strong>What’s next?</strong></h4><p>If you want to go deeper, here’s where to go from here:</p><ul><li><strong>Job Batching with </strong><strong>Bus::batch()</strong> — group related jobs, track progress, run callbacks on completion</li><li><strong>Broadcasting job progress</strong> — combine queues with Laravel Reverb to show a real-time progress bar in your UI <em>(we covered Reverb in a previous article — these two pair really well)<br></em><a href="https://medium.com/@houdaifaboucenna/from-polling-to-real-time-building-a-laravel-12-chat-with-websockets-reverb-0ab51a8120bf">https://medium.com/@houdaifaboucenna/from-polling-to-real-time-building-a-laravel-12-chat-with-websockets-reverb-0ab51a8120bf</a></li><li><strong>Horizontal scaling</strong> — running multiple workers across multiple servers with Redis as the shared backbone</li></ul><h3>🔗 Stay Connected</h3><p>Follow me for more Laravel tutorials, dev tips, deployment workflows and<br>solving real-world production headaches.</p><p><em>➣ Follow me on </em><a href="https://www.linkedin.com/in/houdaifaboucenna/"><strong><em>LinkedIn</em></strong></a><strong><em><br></em></strong><em>➣</em> <em>Follow me </em>here on <a href="https://medium.com/@houdaifaboucenna"><strong><em>Medium</em></strong></a> and <a href="https://medium.com/@houdaifaboucenna/subscribe"><strong><em>join my mailing list</em></strong></a> for more in-depth content and tutorials!<br><em>➣ Follow me on </em><a href="https://dev.to/houdaifa360"><strong><em>D</em>ev.to</strong></a></p><p><strong>Found this article useful?</strong><br>🙏 Show your support by clapping 👏, subscribing 🔔, sharing to social networks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4ba53e62b6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Polling to Real-Time: Building a Laravel 12 Chat with WebSockets & Reverb]]></title>
            <link>https://medium.com/@houdaifaboucenna/from-polling-to-real-time-building-a-laravel-12-chat-with-websockets-reverb-0ab51a8120bf?source=rss-bf318e996aa3------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ab51a8120bf</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[reverb]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Houdaifa Boucenna]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 17:24:57 GMT</pubDate>
            <atom:updated>2026-02-25T17:24:57.849Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered how chat applications deliver messages instantly without overwhelming the server?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pYy6d8SLbglaQrCwq-AQWw.jpeg" /></figure><p>I recently worked on a legacy Laravel application that included a built-in chat system. At first glance, everything seemed functional — messages were sent and received, and the feature “worked.”</p><p>But the experience felt off.</p><p>Messages were delayed. The interface became slower after a few minutes. Opening multiple tabs made things worse. Something clearly wasn’t right.</p><p>After digging into the code, I discovered the issue: the application was repeatedly requesting new messages every few seconds. It was using a technique known as <strong>polling</strong>.</p><p>In other words, every connected user was continuously asking the server:</p><p><em>“Do you have new messages now?” <br>“What about now?”<br>“Now?”</em></p><p>This approach might work for small internal tools, but it doesn’t scale. With enough users, the number of HTTP requests explodes — consuming server resources while still delivering a delayed “real-time” experience.</p><p>That’s when I decided to rebuild the entire chat system using a proper WebSocket-based architecture with Laravel Reverb.</p><p>The difference was dramatic.</p><p>• Latency dropped significantly<br> • HTTP request volume decreased drastically<br> • The UI became truly real-time</p><p>In this article, I’ll walk you through how I built a production-ready WebSocket solution using Laravel 12, Reverb, and Nginx.</p><h3>1. Why Polling Fails at Scale?</h3><p>Polling seems simple.</p><p>The client sends an HTTP request every few seconds asking:</p><blockquote><em>“Do you have new messages?”</em></blockquote><p>If there are new messages, the server responds with them.<br> If not, it returns an empty response.</p><p>At small scale, this works. But let’s look at the math.</p><p>If one user polls every 3 seconds:</p><ul><li>20 requests per minute</li><li>1,200 requests per hour</li></ul><p>Now imagine 100 concurrent users:</p><ul><li>2,000 requests per minute</li><li>120,000 requests per hour</li></ul><p>And most of those requests return… nothing.</p><p>This creates three major problems:</p><p><strong>1️⃣ Massive Waste of Resources:</strong> Every single HTTP request requires the server to accept the connection, bootstrap the Laravel framework, hit the routing layer, check authentication, and likely query the database — just to return an empty JSON array. This eats up CPU and RAM for zero actual payload.</p><p><strong>2️⃣ Artificial Latency:</strong> If a user polls every 3 seconds, and a message is sent right after a poll finishes, the receiving user won’t see it for almost 3 seconds. In a modern chat application, a 3-second delay feels like an eternity.</p><p><strong>3️⃣ Client-Side Degradation:</strong> Opening multiple tabs means multiplying those requests. Browsers limit the number of concurrent connections to the same domain. If your polling clogs up those connections, the rest of your application (like loading images or saving form data) starts to crawl.</p><h3>2. The WebSocket Solution: From Asking to Listening</h3><p>Instead of the client repeatedly asking the server for updates, what if the server just <em>told</em> the client when something happened?</p><p>Enter WebSockets.</p><p>A <strong>WebSocket</strong> creates a persistent, bi-directional, <strong>full-duplex connection</strong> between the client and the server.</p><ul><li><strong>Connect Once:</strong> The client makes a single HTTP request to establish the connection, which is then “upgraded” to a WebSocket.</li><li><strong>Listen Continuously:</strong> The connection stays open with minimal overhead. The client simply waits.</li><li><strong>Push Instantly:</strong> When User A sends a message, the server instantly pushes that payload through the open connection directly to User B.</li></ul><p>Zero wasted requests. Zero artificial delay. True real-time communication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dv0BgXagDhUQLIpDfZr3jA.jpeg" /><figcaption>Generated with Nano Banana</figcaption></figure><h3>3. Laravel Real-Time Options</h3><p>Historically, achieving this in Laravel meant making a tough choice.</p><p>For years, the standard approach was relying on third-party SaaS platforms like Pusher. While incredibly easy to set up, third-party services can become prohibitively expensive as your concurrent connections and daily message limits scale up.</p><p>If you wanted to <strong>self-host </strong>to save costs, you had to venture outside the PHP ecosystem. You might have used <strong>Laravel WebSockets</strong> (which required running a long-lived PHP process that wasn’t natively optimized for it and is now mostly abandoned).</p><p><strong>Then came Laravel Reverb.</strong></p><p>Introduced as a first-party package, <strong>Reverb</strong> is a blazing-fast, highly scalable WebSocket server written entirely in PHP using ReactPHP. It integrates perfectly with Laravel’s existing broadcasting system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*DF2a5zLDFJDw4iWx0nniYw.jpeg" /></figure><h3>4. Setting Up Reverb and Broadcasting</h3><p>With the theory out of the way, let’s get our hands dirty. Since we are using Laravel 12, installing and configuring Reverb is incredibly streamlined.</p><p>Laravel 12 doesn’t enable broadcasting by default, but it provides a single, powerful Artisan command to scaffold everything we need.</p><pre>// Install Broadcasting + Reverb + Node dependencies (Pusher, Echo)<br>php artisan install:broadcasting<br><br>INFO  Published &#39;broadcasting&#39; configuration file.  <br>INFO  Published &#39;channels&#39; route file.  <br><br>┌ Which broadcasting driver would you like to use? ────────────┐<br>│ Laravel Reverb                                               │<br>└──────────────────────────────────────────────────────────────┘<br><br>┌ Would you like to install Laravel Reverb? ───────────────────┐<br>│ Yes                                                          │<br>└──────────────────────────────────────────────────────────────┘<br><br>┌ Would you like to install and build the Node dependencies required for broadcasting? ┐<br>│ Yes                                                                                   │<br>└──────────────────────────────────────────────────────────────────────────────────────┘</pre><p>If you check your .env file, you&#39;ll see Laravel has automatically generated the keys for your local Reverb server:</p><pre>BROADCAST_CONNECTION=reverb<br><br>REVERB_APP_ID=your_generated_id<br>REVERB_APP_KEY=your_generated_key<br>REVERB_APP_SECRET=your_generated_secret<br>REVERB_HOST=&quot;localhost&quot;<br>REVERB_PORT=8080<br>REVERB_SCHEME=http<br><br>VITE_REVERB_APP_KEY=&quot;${REVERB_APP_KEY}&quot;<br>VITE_REVERB_HOST=&quot;${REVERB_HOST}&quot;<br>VITE_REVERB_PORT=&quot;${REVERB_PORT}&quot;<br>VITE_REVERB_SCHEME=&quot;${REVERB_SCHEME}&quot;</pre><p><strong>Starting the Reverb Server: </strong>Now that it’s installed, we need to spin up the actual WebSocket server. Open a new terminal tab (so it runs alongside your standard local web server) and run:</p><pre>php artisan reverb:start</pre><p>🔥 <em>Boom.</em> You now have a blazing-fast, <strong>self-hosted WebSocket server</strong> running on port <strong>8080</strong>.</p><h3>5. Building the Chat System &amp; Firing Events</h3><p>Let’s get straight to the code. We need a lightweight foundation: users, messages, and the event that acts as our messenger.</p><h4>The Data Layer</h4><p>First, we set up a simple Message model linked to our User.</p><pre>php artisan make:model Message -m</pre><p>In your migration, keep it lean — just the essentials to prove the concept:</p><pre>Schema::create(&#39;messages&#39;, function (Blueprint $table) {<br>    $table-&gt;id();<br>    $table-&gt;foreignId(&#39;sender_id&#39;)-&gt;constrained(&#39;users&#39;);<br>    $table-&gt;foreignId(&#39;receiver_id&#39;)-&gt;constrained(&#39;users&#39;);<br>    $table-&gt;text(&#39;body&#39;);<br>    $table-&gt;timestamps();<br>});</pre><h4>The Broadcast Event</h4><p>This is where the magic happens. We generate an event that Laravel will automatically push to Reverb.</p><pre>php artisan make:event MessageSent</pre><p>We need to tweak the generated event to implement the ShouldBroadcastNow interface. This tells Laravel to skip the queue and push the payload to Reverb immediately.</p><pre>class MessageSent implements ShouldBroadcastNow<br>{<br>    use Dispatchable, SerializesModels;<br><br>    public function __construct(public Message $message){}<br><br>    // Securing the channel so only receiver user can listen<br>    public function broadcastOn(): Channel<br>    {<br>        return new PrivateChannel(&#39;chat.&#39; . $this-&gt;message-&gt;receiver_id);<br>    }<br>}</pre><p>⚠️ In high traffic use ShouldBroadcastinterface, this lets <strong>queue</strong> <strong>workers </strong>handle broadcasting and lets the server respond immediately</p><h4>Securing Private Channels</h4><p>Because we are broadcasting on a private channel, we must define its authorization logic.</p><p>Open routes/channels.php and add:</p><pre>use Illuminate\Support\Facades\Broadcast;<br><br>Broadcast::channel(&#39;chat.{userId}&#39;, function ($user, $userId) {<br>    return (int) $user-&gt;id === (int) $userId;<br>});</pre><p>This ensures:</p><ul><li>Only the authenticated user can listen to their own private chat channel</li><li>No user can subscribe to another user’s channel</li></ul><p>Without this, Laravel will reject the WebSocket subscription.</p><h4>Firing the Event</h4><p>When a user submits a new message via your controller, you simply save it to the database and fire the event.</p><pre>public function store(Request $request)<br>{<br>    $message = Message::create([<br>        &#39;sender_id&#39;   =&gt; $request-&gt;user()-&gt;id,<br>        &#39;receiver_id&#39; =&gt; $request-&gt;receiver_id,<br>        &#39;body&#39;        =&gt; $request-&gt;body,<br>    ]);<br><br>    // This sends the pulse ONLY to the receiver&#39;s private channel<br>    broadcast(new MessageSent($message))-&gt;toOthers();<br><br>    return response()-&gt;json($message);<br>}</pre><p>That’s it for the backend — <strong>Reverb</strong> is now catching that event and blasting it out to the connected WebSocket client on the chat.{receiverId} channel.</p><h3>6. Catching the Event &amp; Updating the UI in Real-Time</h3><p>The backend is now broadcasting events through Reverb.</p><p>But broadcasting alone does nothing unless the frontend is actively listening.</p><p>This is where <strong>Laravel Echo</strong> comes into play.</p><h3>Configuring Echo</h3><p>We just need to ensure it matches our .env configuration.</p><pre>// inside (resources/js/bootstrap.js)<br>import Echo from &#39;laravel-echo&#39;;<br>import Pusher from &#39;pusher-js&#39;;<br>window.Pusher = Pusher;<br><br>window.Echo = new Echo({<br>    broadcaster: &#39;reverb&#39;,<br>    key: import.meta.env.VITE_REVERB_APP_KEY,<br>    wsHost: import.meta.env.VITE_REVERB_HOST,<br>    wsPort: import.meta.env.VITE_REVERB_PORT ?? 80,<br>    wssPort: import.meta.env.VITE_REVERB_PORT ?? 443,<br>    forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? &#39;http&#39;) === &#39;https&#39;,<br>    enabledTransports: [&#39;ws&#39;, &#39;wss&#39;],<br>});</pre><p>Let’s break this down:</p><ul><li>key → Must match your REVERB_APP_KEY.</li><li>wsHost and wsPort → Point to your Reverb server.</li><li>forceTLS → Automatically switches to wss:// in production.</li></ul><p>At this point, the browser will establish a persistent WebSocket connection to the Reverb server as soon as your app loads.</p><h3>Listening to the Private Channel</h3><p>Remember our event broadcasted on: chat.{receiver_id}</p><p>And it was defined as a <strong>private channel</strong>. So in the frontend, the authenticated user must subscribe to their own private channel:</p><pre>const userId = window.App.user.id;<br>window.Echo.private(`chat.${userId}`)<br>    .listen(&#39;MessageSent&#39;, (event) =&gt; {<br>        console.log(&#39;New message received:&#39;, event.message);<br>        appendMessage(event.message);<br>    });</pre><p>That’s it.</p><p>No polling. No intervals. No repeated API calls.</p><p>The client is now simply <strong>listening</strong>.</p><p>When the server broadcasts the event, the message arrives instantly through the open WebSocket connection.</p><h3>Updating the UI</h3><p>The handler function might look something like:</p><pre>// chat view (blade, html)<br>function appendMessageToUI(message) {<br>    const chatBox = document.getElementById(&#39;chat-box&#39;);<br>    const messageElement = document.createElement(&#39;div&#39;);<br>    messageElement.classList.add(&#39;message&#39;);<br>    messageElement.innerText = message.body;<br>    chatBox.appendChild(messageElement);<br>}</pre><p>The moment MessageSent is broadcast:</p><ol><li>Reverb pushes it to the browser</li><li>Echo catches it</li><li>Your callback executes</li><li>The DOM updates instantly</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAuPYkTB3FyEQUAtUoiAJA.jpeg" /><figcaption>Socket request established 101 status, messages sent and received</figcaption></figure><h3>7. Real Metrics: Before vs After</h3><p>When migrating from polling to WebSockets, the improvement isn’t theoretical — it’s measurable.</p><p>Let’s compare both approaches in practical terms. (80 concurrent user)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOIzty7f-49NGO3S_TCDJA.jpeg" /></figure><h3>8. Real-World Use Cases Beyond Chat</h3><p>This architecture is not limited to messaging.</p><p>Once WebSockets are in place, you unlock powerful capabilities:</p><h4>🔔 Live Notifications</h4><p>Instant alerts without refreshing the page.</p><h4>📊 Real-Time Dashboards</h4><p>Admin panels that update metrics instantly.</p><h4>📦 Order Tracking</h4><p>Delivery status updates pushed in real-time.</p><h4>🧠 Live Analytics</h4><p>Active user counters, sales metrics, traffic monitoring.</p><h4>🏭 IoT Monitoring</h4><p>Devices pushing sensor data instantly to dashboards.</p><p>Any system where “something happens” and users must see it immediately is a perfect candidate.</p><h3>9. Final Thoughts (Bridge to Part 2)</h3><p>Rebuilding the chat system was only half the journey.</p><p>Moving from polling to WebSockets solved the performance and latency problems — but running WebSockets in production introduces new challenges:</p><ul><li>Reverse proxy configuration</li><li>SSL termination (wss://)</li><li>Process supervision</li><li>Firewall rules</li><li>Scaling strategy</li></ul><p><strong>In Part 2</strong>, I’ll walk through how I deployed Laravel Reverb in production behind Nginx — including the exact configuration, common pitfalls, and the issues I encountered along the way.</p><h3>🔗 Stay Connected</h3><p>Follow me for more Laravel tutorials, dev tips, deployment workflows and<br>solving real-world production headaches.</p><p><em>➣ Follow me on </em><a href="https://www.linkedin.com/in/houdaifaboucenna/"><strong><em>LinkedIn</em></strong></a><strong><em><br></em></strong><em>➣</em> <em>Follow me </em>here on <a href="https://medium.com/@houdaifaboucenna"><strong><em>Medium</em></strong></a> and <a href="https://medium.com/@houdaifaboucenna/subscribe"><strong><em>join my mailing list</em></strong></a> for more in-depth content and tutorials!<br><em>➣ Follow me on </em><a href="https://dev.to/houdaifa360"><strong><em>D</em>ev.to</strong></a></p><p><strong>Found this article useful?</strong><br>🙏 Show your support by clapping 👏, subscribing 🔔, sharing to social networks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ab51a8120bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Laravel to VPS with GitHub Actions (Zero Downtime CI/CD)]]></title>
            <link>https://medium.com/@houdaifaboucenna/deploy-laravel-to-vps-with-github-actions-zero-downtime-ci-cd-529e48035958?source=rss-bf318e996aa3------2</link>
            <guid isPermaLink="false">https://medium.com/p/529e48035958</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[vps]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[cicd]]></category>
            <dc:creator><![CDATA[Houdaifa Boucenna]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 15:34:53 GMT</pubDate>
            <atom:updated>2026-02-15T13:42:13.537Z</atom:updated>
            <content:encoded><![CDATA[<p>Deploying a Laravel application to a freshly created VPS can quickly become overwhelming. There are many ways to put a web application online, and it’s easy to lose focus trying to build the “perfect” deployment workflow — only to end up with something hard to maintain.</p><p>In real projects, what matters most is <strong>a reliable, repeatable, and safe deployment process</strong> that lets you focus on writing code instead of manually pushing changes to servers.</p><p>In this article, I’ll walk through a <strong>minimal yet production-ready CI/CD approach</strong> for deploying Laravel applications to a VPS (or EC2 instance) using <strong>GitHub Actions and SSH</strong>.</p><p>⚠️ The goal is not to cover every possible optimization, but to present a workflow that works well for real client projects and personal products.</p><blockquote><strong><em>💡 Not on a VPS yet?</em></strong><em> This guide focuses on automated deployment for servers where you have full root privileges. If you are stuck with </em><strong><em>Shared Hosting (cPanel)</em></strong><em> and don’t have SSH access, check out my alternative guide: 👉 </em><a href="https://medium.com/@houdaifaboucenna/deploying-laravel-on-shared-hosting-no-ssh-required-34b409efc7ae"><strong><em>How to Deploy Laravel on Shared Hosting (No SSH Required)</em></strong></a></blockquote><h3>Stack Used</h3><p>To keep things concrete, this guide assumes the following setup:</p><ul><li>Ubuntu Server (20.04+)</li><li>Laravel 12 with PHP 8.3</li><li>Nginx + PHP-FPM</li><li>MySQL</li><li>GitHub Actions for CI/CD</li></ul><p>This guide assumes basic familiarity with Linux and Laravel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uwJ_sa8RGdzPGihrKdJSgg.png" /></figure><h3>Step 1 — Installing Server Requirements</h3><p>After connecting to your server via SSH, it’s recommended <strong>not to work as root</strong>, but as a sudo-enabled user.</p><p>The key idea here is that <strong>this setup is done once</strong>. After the initial server preparation, deployments should not require installing system dependencies again.</p><pre># Update system list and upgrade packages<br>sudo apt update &amp;&amp; sudo apt upgrade -y<br><br># Install Nginx<br>sudo apt install nginx -y<br><br># Install Mysql Server<br>sudo apt install mysql-server -y<br><br># Install PHP and required Packages<br>sudo apt install php-cli php-fpm php-mysql php-xml php-mbstring php-curl unzip -y<br><br># Install Composer <br>sudo curl -sS https://getcomposer.org/installer | php<br>sudo mv composer.phar /usr/local/bin/composer<br><br># Install Node.js and NPM<br>curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -<br>sudo apt install -y nodejs</pre><p>⚠️ Be careful to install a PHP version that matches your Laravel version requirements. Mismatches here are a common source of production issues.</p><h3>Step 2 — Configuring Nginx for Laravel</h3><p>We need to configure Nginx to point to the current/public directory (which we will create later via our CI/CD pipeline). Let&#39;s create configs:<br>sudo touch /etc/nginx/sites-available/laravel-app</p><pre>server {<br>    listen 80;<br>    server_name your-domain.com;<br><br>    # POINT TO &#39;current/public&#39; FOR ATOMIC DEPLOYMENTS<br>    root /var/www/laravel-app/current/public;<br><br>    add_header X-Frame-Options &quot;SAMEORIGIN&quot;;<br>    add_header X-Content-Type-Options &quot;nosniff&quot;;<br><br>    index index.php;<br>    charset utf-8;<br><br>    location / {<br>        try_files $uri $uri/ /index.php?$query_string;<br>    }<br><br>    location = /favicon.ico { access_log off; log_not_found off; }<br>    location = /robots.txt  { access_log off; log_not_found off; }<br><br>    error_page 404 /index.php;<br><br>    location ~ \.php$ {<br>        fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;<br>        fastcgi_index index.php;<br>        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;<br>        include fastcgi_params;<br>    }<br><br>    location ~ /\.(?!well-known).* {<br>        deny all;<br>    }<br>}</pre><p>Then, we enable the configuration and ensure it is working</p><pre>sudo ln -s /etc/nginx/sites-available/laravel-app /etc/nginx/sites-enabled/<br>sudo unlink /etc/nginx/sites-enabled/default<br>sudo nginx -t<br>sudo systemctl restart nginx</pre><p>⚠️ Replace your-domain.com with your actual domain.</p><h3>Step 3 — Set up MySQL server and create a database</h3><p>Let&#39;s execute the MySQL security script</p><pre># Secure MySQL (set root password, remove anonymous users)<br>sudo mysql_secure_installation<br><br># Log in to MySQL<br>sudo mysql -u root -p</pre><p>Then, we create the application database that we will use</p><pre>CREATE DATABASE laravel_db;<br>CREATE USER &#39;laravel_user&#39;@&#39;localhost&#39; IDENTIFIED BY &#39;your-strong-password&#39;;<br>GRANT ALL PRIVILEGES ON laravel_db.* TO &#39;laravel_user&#39;@&#39;localhost&#39;;<br>FLUSH PRIVILEGES;<br>EXIT;</pre><p>Once created, we should add the database access in the production .env<br>⚠️ The .env is never committed to Git and is created only once on the server. CI/CD pipelines should never modify it.</p><h3>Step 4 — Initializing the Application on the Server</h3><p>Before automation, we need to set up the folder structure. We will create a “<strong>shared</strong>” structure so that logs and uploads persist between deployments.</p><pre># 1. Create the main directory<br>sudo mkdir -p /var/www/laravel-app<br>sudo chown -R $USER:www-data /var/www/laravel-app<br><br># 2. Setup the persistent folders<br>cd /var/www/laravel-app<br>mkdir -p shared/storage/framework/{cache/data,sessions,views}<br><br># 3. Create the .env file<br>nano shared/.env<br># (Paste your production env content here)<br><br># 4. Set permissions ONE TIME<br>sudo chown -R $USER:www-data /var/www/laravel-app<br>sudo chmod -R 775 shared/storage</pre><h3>Step 5 — CI/CD Strategy with GitHub Actions</h3><p>Instead of running Composer and NPM commands directly on the server, the deployment workflow follows a <strong>build-then-deploy</strong> strategy:</p><h4>Why build in CI instead of the server?</h4><ul><li>Faster deployments</li><li>More predictable results</li><li>Fewer production dependencies</li><li>Easier debugging</li><li>Reduced server load</li></ul><p><strong>In this approach:</strong></p><ol><li>GitHub Actions installs PHP and Node</li><li>Composer dependencies are installed</li><li>Frontend assets are built</li><li>A clean release artifact is generated</li><li>The artifact is deployed to the server via SSH</li><li>A new release directory is created</li><li>The current symlink is updated atomically</li></ol><p>The server becomes a <strong>stable runtime environment</strong>, not a build machine.</p><p>Create .github/workflows/deploy.yml in your Laravel project</p><pre>name: Deploy Laravel to VPS<br><br>on:<br>  push:<br>    branches: [ main ]<br><br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>    # 1️⃣ Checkout Code<br>    - name: Checkout repository<br>      uses: actions/checkout@v4<br><br>    # 2️⃣ Setup PHP<br>    - name: Setup PHP<br>      uses: shivammathur/setup-php@v2<br>      with:<br>        php-version: 8.3<br>        extensions: mbstring, xml, ctype, iconv, intl, pdo_mysql<br><br>    # 3️⃣ Install Backend Dependencies<br>    - name: Install Composer dependencies<br>      run: |<br>        composer install --no-dev --prefer-dist --optimize-autoloader<br><br>    # 4️⃣ Build Frontend Assets<br>    - name: Setup Node &amp; Build<br>      uses: actions/setup-node@v4<br>      with:<br>        node-version: 20<br>    - run: |<br>        npm ci<br>        npm run build<br><br>    # 5️⃣ Prepare Files for Transfer<br>    - name: Archive application<br>      run: |<br>        tar --exclude=&#39;./storage&#39; \<br>            --exclude=&#39;./.git&#39; \<br>            --exclude=&#39;./node_modules&#39; \<br>            --exclude=&#39;./tests&#39; \<br>            -czf /tmp/release.tar.gz .<br><br>        # 2. Move it back to the workspace<br>        mv /tmp/release.tar.gz .<br><br>    # 6️⃣ Upload to Server<br>    - name: Upload artifact via SCP<br>      uses: appleboy/scp-action@master<br>      with:<br>        host: ${{ secrets.VPS_HOST }}<br>        username: ${{ secrets.VPS_USERNAME }}<br>        key: ${{ secrets.VPS_SSH_KEY }}<br>        port: ${{ secrets.VPS_PORT || 22 }}<br>        source: &quot;release.tar.gz&quot;<br>        target: &quot;/var/www/laravel-app&quot;<br><br>    # 7️⃣ Deploy on Server<br>    - name: Execute Remote SSH Commands<br>      uses: appleboy/ssh-action@master<br>      with:<br>        host: ${{ secrets.VPS_HOST }}<br>        username: ${{ secrets.VPS_USERNAME }}<br>        key: ${{ secrets.VPS_SSH_KEY }}<br>        port: ${{ secrets.VPS_PORT || 22 }}<br>        script: |<br>          set -e<br><br>          APP_DIR=&quot;/var/www/laravel-app&quot;<br>          RELEASE_ID=$(date +%Y%m%d%H%M%S)<br>          RELEASE_PATH=&quot;$APP_DIR/releases/$RELEASE_ID&quot;<br><br>          # 1. Create new release directory<br>          mkdir -p $RELEASE_PATH<br><br>          # 2. Extract files<br>          tar -xzf $APP_DIR/release.tar.gz -C $RELEASE_PATH<br>          rm $APP_DIR/release.tar.gz<br><br>          # 3. Link Shared Resources<br>          ln -sfn $APP_DIR/shared/.env $RELEASE_PATH/.env<br>          ln -sfn $APP_DIR/shared/storage $RELEASE_PATH/storage<br><br>          # 4. Set Permissions<br>          sudo chown -R $USER:www-data $RELEASE_PATH<br>          <br>          # Ensure group write access for cache (so webserver can write to it)<br>          sudo chmod -R 775 $RELEASE_PATH/bootstrap/cache<br><br>          # 5. Run Migrations &amp; Storage Link &amp; Optimize &amp; Reload<br>          cd $RELEASE_PATH<br>          php artisan migrate --force<br>          php artisan storage:link<br>          php artisan optimize<br>          php artisan reload<br><br>          # 6. Atomic Switch (Zero Downtime)<br>          ln -sfn $RELEASE_PATH $APP_DIR/current<br><br>          # 7. Reload PHP-FPM (Ensure this matches your server version!)<br>          sudo systemctl reload php8.3-fpm<br><br>          # 8. Cleanup old releases (keep latest 5) <br>          cd $APP_DIR/releases<br>          ls -t | tail -n +6 | xargs -r rm -rf<br><br>          echo &quot;🚀 Deployment $RELEASE_ID success!&quot;</pre><p>In your GitHub repository:</p><ol><li>Go to Settings → Secrets and variables → Actions</li><li>Add these secrets:</li></ol><ul><li>VPS_HOST: Your VPS IP address</li><li>VPS_USERNAME: SSH username</li><li>VPS_SSH_KEY: Private SSH key</li><li>VPS_PORT: SSH port (default: 22)</li></ul><h3>Step 6 — Release-Based Deployment Flow</h3><p>Each deployment creates a new release directory:</p><pre>/var/www/laravel-app/releases/20260210151258</pre><p>Shared directories such as storage and bootstrap/cache are symlinked into each release.</p><p>Once everything is ready:</p><ul><li>Database migrations are executed with --force</li><li>Caches are optimized</li><li>The current symlink is switched to the new release</li></ul><p>⚡ Because the symlink update is atomic, <strong>users rarely notice downtime</strong>.</p><h3>Troubleshooting Common Issues</h3><h3>500 Internal Server Error</h3><p>Most commonly caused by:</p><ul><li>Incorrect file permissions</li><li>Missing PHP extensions</li><li>Wrong PHP-FPM socket version</li><li>Broken symlink paths</li></ul><p>Check that storage/ and bootstrap/cache/ are writable.</p><h3>Blank Page After Deployment</h3><p>Often caused by:</p><ul><li>Incorrect Nginx root path</li><li>Missing .env</li><li>Application key not generated</li></ul><p>Make sure:</p><pre>APP_ENV=production<br>APP_DEBUG=false</pre><h3>SSH Action Fails</h3><p>Usually due to:</p><ul><li>Incorrect private key format</li><li>Wrong SSH username</li><li>Server firewall rules</li></ul><p>Test SSH access manually before debugging CI.</p><h3>Final Thoughts</h3><p>This setup gives you a professional, automated pipeline. You push to main, and GitHub Actions handles the rest — running tests, building assets, and switching the live site without dropping connections.</p><p><strong>Happy Deploying! 🚀</strong></p><h3>🔗 Stay Connected</h3><p>Follow me for more Laravel tutorials, dev tips, deployment workflows and<br>solving real-world production headaches.</p><p><em>➣ Follow me on </em><a href="https://www.linkedin.com/in/houdaifaboucenna/"><strong><em>LinkedIn</em></strong></a><strong><em><br></em></strong><em>➣</em> <em>Follow me </em>here on <a href="https://medium.com/@houdaifaboucenna"><strong><em>Medium</em></strong></a> and <a href="https://medium.com/@houdaifaboucenna/subscribe"><strong><em>join my mailing list</em></strong></a> for more in-depth content and tutorials!<br><em>➣ Follow me on </em><a href="https://dev.to/houdaifa360"><strong><em>D</em>ev.to</strong></a></p><p><strong>Found this article useful?</strong><br>🙏 Show your support by clapping 👏, subscribing 🔔, sharing to social networks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=529e48035958" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Laravel on Shared Hosting (No SSH Required)]]></title>
            <link>https://medium.com/@houdaifaboucenna/deploying-laravel-on-shared-hosting-no-ssh-required-34b409efc7ae?source=rss-bf318e996aa3------2</link>
            <guid isPermaLink="false">https://medium.com/p/34b409efc7ae</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[shared-hosting]]></category>
            <category><![CDATA[cpanel]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Houdaifa Boucenna]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 10:37:08 GMT</pubDate>
            <atom:updated>2026-02-13T21:33:41.427Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered if you can deploy a Laravel application on shared hosting without SSH?</p><p>The answer is YES, I faced this exact situation during my early freelance journey: a client with a tight budget needed to see the first version of his Laravel website online before moving forward. The hosting environment had <strong>no SSH, no Composer, no Artisan, no NPM</strong>.</p><p>So I had to figure out a safe and reliable alternative.</p><p>In this article, I’ll share the exact workflow I use to deploy Laravel applications on shared hosting <strong>without SSH access</strong>.</p><blockquote>When you are ready to upgrade to a dedicated server and want to automate everything, check out my professional guide: 👉 <a href="https://medium.com/@houdaifaboucenna/deploy-laravel-to-vps-with-github-actions-zero-downtime-ci-cd-529e48035958"><strong>Deploy Laravel to VPS with GitHub Actions (Zero Downtime CI/CD)</strong></a>”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2BXXUv_yJ0-VscbrzN49Rw.png" /></figure><h3>Why Laravel Deployment on Shared Hosting Is Different</h3><h3>1. Project File Structure</h3><p>A typical Laravel project looks like this:</p><pre>project/<br> ├── app/<br> ├── bootstrap/<br> ├── config/<br> ├── public/<br> ├── storage/<br> ├── vendor/<br> └── artisan</pre><p>However, shared hosting usually exposes only one public directory:</p><pre>├── public_html/</pre><h3>2. No SSH, No commands</h3><p>If there is SSH access, obviously, there will be:<br>1. No composer dependencies can be installed<br>2. No asset building since we no longer have “npm run”<br>3. No migrations can executed<br>4. No cache clearing or optimizing</p><h3>How to solve the situation step-by-step</h3><h3>Step1: Prepare Your Application Locally</h3><p>First, I clone my Laravel project into a production-ready copy so I don’t affect my development setup:</p><pre>├── laravel_app/<br>├── laravel_app_prod/</pre><p>Inside laravel_app_prod, I prepare the application for production.</p><pre>// clearing the cache<br>php artisan config:clear<br>php artisan cache:clear<br>php artisan route:clear<br>php artisan view:clear<br><br>// installing production dependencies and optimize<br>composer install --no-dev --optimize-autoloader<br><br>// building frontend assets<br>npm run build</pre><h3>Step 2 — Re-organize Project File Structure</h3><p>To match shared hosting file structure, I move only public/ folder content inside the new public_html/folder, like this:</p><pre>public_html/  &lt;-------------------|<br>laravel_app_prod/                 |<br> ├── app/                         |<br> ├── bootstrap/                   |<br> ├── config/                      |<br> ├── public/ ---------------------|<br> ├── storage/           <br> ├── vendor/            <br> └── artisan            </pre><h3>Step 3 — Fix Laravel Paths in index.php</h3><p>Now, we should do one important step to make the app boot correctly, so we update the paths in <em>public/index.php</em></p><pre>if (file_exists(<br>    $maintenance = __DIR__ . &#39;/../laravel_app_prod/storage/framework/maintenance.php&#39;)<br>) {<br>    require $maintenance;<br>}<br><br>require __DIR__ . &#39;/../laravel_app_prod/vendor/autoload.php&#39;;<br><br>(require_once __DIR__ . &#39;/../laravel_app_prod/bootstrap/app.php&#39;)<br>    -&gt;handleRequest(Request::capture());</pre><p>This is a critical step — incorrect paths will cause a 500 error.</p><h3>Step 4 — Set Up The Database Using cPanel</h3><p>From cPanel:</p><ol><li>Open <strong>MySQL Database Wizard</strong></li><li>Create a database</li><li>Create a database user</li><li>Assign the user <strong>ALL PRIVILEGES</strong></li></ol><p>Then update the .env file inside laravel_app_prod:</p><pre>APP_NAME=MyApp<br>APP_ENV=production<br>APP_DEBUG=false          // very important (security)<br>APP_URL=https://your-app-domain<br><br>DB_DATABASE=database_name<br>DB_USERNAME=database_user<br>DB_PASSWORD=database_password  // (you already saved it)</pre><p>⚠️ <strong>Never enable </strong><strong>APP_DEBUG=true in production.</strong></p><h3>Step 5 — Temporary Deploy Route (Token Protected)</h3><p>Coming to the important part, no SSH, no problem, we can temporarily execute Artisan commands via a <strong>protected web route</strong>.</p><p>⚠️ This route <strong>must be removed immediately after deployment</strong>.</p><p>Add a secret token to .env:</p><pre>DEPLOY_TOKEN=verySecretRandomToken123</pre><p>Add the route in routes/web.php:</p><pre>use Illuminate\Support\Facades\Artisan;<br>use Illuminate\Support\Facades\Route;<br>Route::get(&#39;/deploy/{token}&#39;, function ($token) {<br>  abort_unless($token === env(&#39;DEPLOY_TOKEN&#39;), 403);<br>  <br>  // 1. Run Migrations &amp; Clear Cache<br>  Artisan::call(&#39;migrate&#39;, [&#39;--force&#39; =&gt; true]);<br>  Artisan::call(&#39;optimize:clear&#39;);<br>  <br>  // 2. Fix Storage Link (The Custom Fix)<br>  // We point to the &#39;public_html&#39; folder using $_SERVER[&#39;DOCUMENT_ROOT&#39;]<br>  $targetFolder = storage_path(&#39;app/public&#39;);<br>  $linkFolder = $_SERVER[&#39;DOCUMENT_ROOT&#39;] . &#39;/storage&#39;;<br>  <br>  if (!file_exists($linkFolder)) {<br>    symlink($targetFolder, $linkFolder);<br>    $storageStatus = &#39;Storage link created successfully.&#39;;<br>  } else {<br>    $storageStatus = &#39;Storage link already exists.&#39;;<br>  }<br>  <br>  return &quot;Deployment completed.&lt;br&gt;&quot; .<br>      &quot;Migrations run.&lt;br&gt;&quot; .<br>      &quot;Cache cleared.&lt;br&gt;&quot; .<br>      $storageStatus;<br>});</pre><p>This ensures only someone with the correct token can trigger deployment.</p><h3>Step 6 — Upload Files to the Server</h3><p>Using <strong>cPanel File Manager</strong>:</p><ol><li>Zip laravel_app_prod/</li><li>Zip the contents of public/</li><li>Upload:<br> .putlaravel_app_prod <strong>outside</strong> public_html<br> .public files <strong>inside</strong> public_html</li></ol><p>Then extract both archives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ribIjWArCPK7t0VN9x426g.png" /></figure><p><strong>Why did we put </strong><strong>laravel_app_prod outside </strong><strong>public_html?</strong> This is a crucial security measure. By placing your core application logic, and most importantly your <strong>.env file</strong>, one level <em>above</em> the public directory, you ensure that they are <strong>physically impossible</strong> to access via a web browser.</p><p>Even if your server misconfigures and starts serving PHP files as text (which happens!), your credentials remain hidden because they live outside the public root.</p><h3>Step 7 — Set Critical Permissions</h3><p>Laravel requires write access to specific folders. If these aren’t set, your logs won’t write and sessions won’t save.</p><ol><li>In cPanel File Manager, navigate to laravel_app_prod/storage.</li><li>Right-click → <strong>Change Permissions</strong>.</li><li>Set to <strong>775</strong> (User: Read/Write/Execute, Group: Read/Write/Execute, World: Read/Execute).</li><li>Do the same for laravel_app_prod/bootstrap/cache.</li></ol><p>🛑 <strong><em>Note</em></strong><em>: Never set folders to 777. It is a major security risk on shared hosting.</em></p><h3>Step 8 — Run Migrations and Remove the Deploy Route</h3><p>Open in the browser:</p><pre>https://your-domain.com/deploy/verySecretRandomToken123</pre><p>If everything is correct, you’ll see:</p><pre>Deployment completed successfully</pre><p>Immediately after that:</p><p>❗ Delete the deploy route<br>❗ Remove DEPLOY_TOKEN from .env</p><p>This is critical for security.</p><h3>Common Issues Faced</h3><h3>500 Internal Server Error</h3><ul><li>Incorrect file paths in index.php</li><li>Wrong PHP version (use cPanel <strong>MultiPHP Manager</strong>)</li><li>Incorrect folder permissions (storage 775, bootstrap/cache 775)</li></ul><h3>403 Unauthorized</h3><ul><li>Unmatched route token with DEPLOY_TOKEN</li></ul><h3>Final Thoughts</h3><p>Shared hosting is not ideal for Laravel, but it’s still very common for:</p><ul><li>Client projects</li><li>MVPs</li><li>Budget-constrained deployments</li></ul><p>With proper preparation and a secure workflow, Laravel applications can run reliably even <strong>without SSH access</strong>.</p><p><strong>💡 Pro Tip: The Safer Database Alternative</strong> If you are uncomfortable running migrations via a web route (which carries security risks), you can use the <strong>Export/Import method</strong>:</p><ol><li>Run migrations on your <strong>local</strong> machine.</li><li>Export your local database as an .sql file using your local tool.</li><li>Go to <strong>cPanel &gt; phpMyAdmin</strong> on the server.</li><li>Import the .sql file directly. This is safer because it doesn&#39;t require executable logic in your production routes.</li></ol><h3>🔗 Stay Connected</h3><p>Follow me for more Laravel tutorials, dev tips, deployment workflows and <br>solving real-world production headaches.</p><p><em>➣ Follow me on </em><a href="https://www.linkedin.com/in/houdaifaboucenna/"><strong><em>LinkedIn</em></strong></a><strong><em><br></em></strong><em>➣</em> <em>Follow me </em>here on <a href="https://medium.com/@houdaifaboucenna"><strong><em>Medium</em></strong></a> and <a href="https://medium.com/@houdaifaboucenna/subscribe"><strong><em>join my mailing list</em></strong></a> for more in-depth content and tutorials!<br><em>➣ Follow me on </em><a href="https://dev.to/houdaifa360"><strong><em>D</em>ev.to</strong></a></p><p><strong>Found this article useful?</strong><br>🙏 Show your support by clapping 👏, subscribing 🔔, sharing to social networks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34b409efc7ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>