<?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 Suman Shrestha on Medium]]></title>
        <description><![CDATA[Stories by Suman Shrestha on Medium]]></description>
        <link>https://medium.com/@iamsuman066?source=rss-480fb83e08cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Suman Shrestha on Medium</title>
            <link>https://medium.com/@iamsuman066?source=rss-480fb83e08cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 07:42:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iamsuman066/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[Service Workers In JavaScript]]></title>
            <link>https://medium.com/@iamsuman066/service-workers-in-javascript-025b4848aeb9?source=rss-480fb83e08cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/025b4848aeb9</guid>
            <category><![CDATA[service-worker]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Suman Shrestha]]></dc:creator>
            <pubDate>Tue, 12 May 2026 03:50:32 GMT</pubDate>
            <atom:updated>2026-05-12T03:50:32.536Z</atom:updated>
            <content:encoded><![CDATA[<p>Service worker acts as a proxy server between web browsers and servers, they have the ability to intercept the network requests and caching api, enabling the offline experiences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ocXdzGiBJLXNJ5aa" /><figcaption>Photo by <a href="https://unsplash.com/@lightsbee?utm_source=medium&amp;utm_medium=referral">Kounotori</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>PWA</strong></p><p>Progressive Web Applications are those apps that provide native application experience, with offline abilities and caches. They are installable, and can do push notifications as well.</p><p>Steps for service worker</p><ol><li>Installation</li><li>Activation</li><li>Interception</li></ol><p>We need to make sure service workers are registered first.</p><p>While service workers can be used for Network First Strategies or Cache First Strategies, we need to learn about</p><ol><li>Precaching (Build time static assets caching)</li><li>Runtime Caching (Api calls)</li></ol><p>Precaching</p><p>During the installation of the services workers, the static assets that are included in the config can be cached or are cached.</p><pre> &lt;script&gt;<br>        window.addEventListener(&quot;load&quot;, () =&gt; {<br>            // check if service worker is available<br>            if(&quot;serviceWorker&quot; in navigator){<br>                navigator.serviceWorker.register(&quot;service-worker.js&quot;, {<br>                    scope: &quot;/&quot;<br>                })<br>            }<br>        })<br>    &lt;/script&gt;</pre><p>First, wait till the app loads, then check if the service worker is supported in the client machine, then register the service worker file i.e. <a href="http://service-worker.js/">service-worker.js</a>.</p><p>2. Installation</p><p>Once the service worker is done registering, service worker fires the <strong><em>install </em></strong>event. This call can only be made once per service worker.</p><pre>self.addEventListener(&quot;install&quot;, (event) =&gt; {<br>  const cacheKey = &quot;name we want to save&quot;<br><br>  event.waitUntil(<br>    caches.open(cacheKey)<br>    .then(cache =&gt; {<br>    // Add all the assets in the array to the cacheKey<br>      return cache.addAll([<br>        //lists of assets<br>      ])<br>  }))<br>})</pre><p>So here, during installation, we could cache the assets in the cache storage.</p><p>The <strong><em>event.waitUntil </em></strong>waits until the assets have been added to the cache storage</p><p>cache.open(cacheName) returns the existing cache, if not creates it and return</p><p>And addAll is adding assets to the storage.</p><p>3. Activation</p><p>Once the registration and installation completes, the status becomes “activating”</p><p>The service worker can be activated with the “activate” event. In this section, we can prune the old cache, and after page reload, the service worker begins to control the web app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=025b4848aeb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript: Temporal Dead Zone(TDZ)]]></title>
            <link>https://medium.com/@iamsuman066/javascript-temporal-dead-zone-tdz-c8065b44faa4?source=rss-480fb83e08cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8065b44faa4</guid>
            <category><![CDATA[js]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-hoisting]]></category>
            <category><![CDATA[const-vs-let-vs-var]]></category>
            <category><![CDATA[temporal-dead-zone]]></category>
            <dc:creator><![CDATA[Suman Shrestha]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 16:38:33 GMT</pubDate>
            <atom:updated>2026-03-31T16:39:51.010Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_SaBAVXldhOrDX5MYspHmQ.jpeg" /><figcaption>cover image</figcaption></figure><p>Well, we must have heard about this <em>temporal dead zone</em> in interview or when we are learning about the hoisting in JavaScript, right?</p><p>Let’s understand it, so we can answer it confidently, next time someone asks us.</p><p>Before that, let’s revise the hoisting part.</p><p><strong><em>Hoisting</em></strong> is the process where JavaScript moves the declaration of the variables and function and classes to their scope.</p><p>Now, we talk about the difference between variables, <strong><em>let, </em></strong><strong><em>const </em></strong>and<strong><em> </em></strong><strong><em>var.</em></strong></p><p>All of these are hoisted, but <strong><em>var</em></strong> is initialized with <strong><em>undefined</em></strong> while <strong><em>let</em></strong> and <strong><em>const</em></strong> are in temporal dead zone.</p><pre>console.log(x);<br><br>var x = 10;<br><br>// Output =&gt; undefined<br><br>console.log(y);<br><br>let y = 10;<br><br>// Output: ReferenceError: Cannot access &#39;y&#39; before initialization</pre><p><strong>So, what is this temporal dead zone?</strong></p><p>To keep it simple, JavaScript has two phases, <strong><em>creation and </em></strong><strong><em>execution.</em></strong></p><p>In creation phase, <strong>memory</strong> is allocated and <strong>variables</strong> are <strong>hoisted</strong>.</p><p>Since, we tried to access the <strong><em>y</em></strong> before its <strong><em>initialization</em></strong>, it returns the <strong><em>reference error.</em></strong></p><p><strong>Thus</strong>, <strong>temporal dead zone is the time difference or a period between entering scope and initialization of the variable.</strong></p><p>One thing to keep in mind, TDZ depends on execution order, not just where the variable is written in the code.</p><pre>{<br>  const func = () =&gt; console.log(val);<br><br>  // Inside TDZ<br>  func();<br>  // Inside TDZ<br><br>  const val = &quot;something&quot;;<br>}<br><br>// Output: ReferenceError: Cannot access &#39;val&#39; before initialization</pre><p>On contrast,</p><pre>{<br>  const func = () =&gt; console.log(val);<br><br>  // Inside TDZ<br><br>  const val = &quot;something&quot;;<br>  // Outside TDZ<br>  func();<br>}<br><br>// Output: &quot;something&quot;</pre><p>Apart from variables, <strong>class</strong> is also hoisted but are in temporal dead zone as well.</p><p>To wrap everything up, we need to understand TDZ exists to prevent unwanted bugs.</p><pre>let count = 10;<br><br>if (true) {<br>  console.log(count); // ReferenceError<br>  let count = 20;<br>}<br><br>// Without TDZ, JavaScript might use the outer count,<br>// which could lead to unpredicatble behavior.</pre><p>Wait one another thing, do you know what is the output of this?</p><pre>a();<br>let a = () =&gt; console.log(&quot;Hello, world&quot;);</pre><p>Hope you liked it haha, see yah!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8065b44faa4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Promises]]></title>
            <link>https://medium.com/@iamsuman066/javascript-promises-79a8fac6e0e3?source=rss-480fb83e08cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/79a8fac6e0e3</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[javascript-promise]]></category>
            <dc:creator><![CDATA[Suman Shrestha]]></dc:creator>
            <pubDate>Fri, 20 Mar 2026 16:05:17 GMT</pubDate>
            <atom:updated>2026-03-20T16:05:17.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IqD2gV2MXC2_KP7MLRYkJg.jpeg" /></figure><p>You must have come across <strong>JavaScript Promises</strong> during the asynchronous programming. Today, we will try to simplify it.</p><p>Well, P<strong>romises</strong> in JavaScript is a placeholder object for the asynchronous operation. When we start an asynchronous operation, the promise is in pending state, and when the promise is settled, handlers deal with either success(fulfilled) or failure(rejected).</p><p>This combination of state and handlers is what makes the promise.</p><p>Once the promise is settled, we cannot change its state.</p><p>Promise itself runs synchronously, and every operations inside the Promise runs synchronously, handlers are what creates the micro tasks.</p><pre>const test = new Promise((resolve) =&gt; {<br>  // everything inside the executor function runs synchronously<br>  console.log(&quot;First&quot;);<br>  resolve(true); //resolved here -&gt;proceeds synchronously<br>  console.log(&quot;Second&quot;);<br>});<br><br>//this creates microtask<br>test.then((data) =&gt; console.log(data)); //prints true<br><br>//output<br>// First<br>// Second<br>// true</pre><p>Promise handlers (<strong><em>then, catch, finally</em></strong>) schedule their callbacks in the <strong>micro-task queue</strong>, which runs after the current synchronous code completes.</p><p>There are few methods, which will be discussed below.</p><ol><li><strong>Promise.all()</strong></li></ol><pre>const promise1 = Promise.resolve(2);<br>const promise2 = Promise.reject(3);<br>const promise3 = Promise.reject(23);<br><br>const test2 = Promise.all([promise1, promise2, promise3]);<br><br>test2<br>.then((data) =&gt; console.log(data))<br>.catch((error) =&gt; console.log(error));<br><br>//output<br>// 3<br>// exits immediately after promise2 that rejects</pre><p><strong>all() </strong>can be used to aggregate multiple promises, concurrently. It returns the promise object with state and value if fulfilled, else reason, and will reject immediately upon <strong>any</strong> of the input promises rejecting.</p><p>2. <strong>Promise.allSettled()</strong></p><pre>const promise1 = Promise.resolve(2);<br>const promise2 = Promise.reject();<br>const promise3 = Promise.reject(23);<br><br>const test2 = Promise.allSettled([promise1, promise2, promise3]);<br><br>test2<br>.then((data) =&gt; console.log(data))<br>.catch((error) =&gt; console.log(error));<br><br>//output<br>// [<br>//   { status: &#39;fulfilled&#39;, value: 2 },<br>//   { status: &#39;rejected&#39;, reason: undefined },<br>//   { status: &#39;rejected&#39;, reason: 23 }<br>// ]<br>// regardless of reject or fulfill, allSettled runs all operations</pre><p><strong>allSettled() </strong>returns the promise with the results of each promises regardless of failure or fullfill.</p><p>3. Promise.any()</p><pre>const promise1 = Promise.resolve(2);<br>const promise2 = Promise.reject();<br>const promise3 = Promise.reject(23);<br><br>const test2 = Promise.any([promise1, promise2, promise3]);<br><br>test2<br>.then((data) =&gt; console.log(data))<br>.catch((error) =&gt; console.log(error));<br><br>//output<br>// 2<br>// exits immediately after first promise fulfills</pre><p><strong>any() </strong>returns the promise with the results of the first promise fullfillment.</p><p>4. Promise.race()</p><pre>const promise1 = Promise.resolve(2);<br>const promise2 = Promise.reject({ error: &quot;Testing error&quot; });<br>const promise3 = Promise.reject(23);<br><br>const test2 = Promise.race([promise2, promise1, promise3]);<br><br>test2<br>.then((data) =&gt; console.log(data))<br>.catch((error) =&gt; console.log(error));<br><br>//output<br>// { error: &#39;Testing error&#39; }<br>// exits with the value of the first settled promise<br>// regardless of fullfillment or not</pre><p><strong>any() </strong>returns the promise with the results of the first promise settlement(can be resolved or rejected).</p><p>Well, promise was created to solve the problems of the callback hell, and async await is the syntactic sugar for the promise.</p><pre><br>async function getBanana() {<br>  const res = await fetch(&quot;https://banana.com/banana/1&quot;);<br>  const data = await res.json();<br>  console.log(data);<br>}<br><br>fetch(&quot;https://banana.com/banana/1&quot;)<br>.then((res) =&gt; res.json())<br>.then((data) =&gt; console.log(data));</pre><p>These two are equivalent, they work exactly same underneath, just the syntax is different.</p><p>Well, I would like to end the chapter of the JavaScript promises here. Glad you stuck here. See ya!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79a8fac6e0e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Oriented Programming in JavaScript]]></title>
            <link>https://medium.com/@iamsuman066/object-oriented-programming-in-javascript-6757007e68ad?source=rss-480fb83e08cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6757007e68ad</guid>
            <category><![CDATA[javascript-prototype]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Suman Shrestha]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 17:25:58 GMT</pubDate>
            <atom:updated>2026-03-15T17:25:58.825Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2mY3F6TzsmJ5xclAA9-eyw.jpeg" /><figcaption>OOP JavaScript</figcaption></figure><p>Object Oriented Programming in JavaScript uses a <strong>prototype-based model</strong> rather than the traditional class-based (blueprint) model used in languages like Java.</p><p>In JavaScript, objects can inherit behaviors from other objects <strong>via prototype chaining</strong>. Instead of copying methods into every instance, methods are shared through a prototype, which reduces memory consumption.</p><p>When we access a property or method on an object, JavaScript first checks the object itself. If it doesn’t exist, the engine looks up the <strong>prototype chain</strong> until it finds the property or reaches <strong>null</strong>.</p><p>Before that, let’s clear up <strong>something</strong>.</p><p><strong>What does it mean that JavaScript is a prototype-based language instead of class based?</strong></p><pre>class Car {<br>  constructor(name, model) {<br>    this.name = name;<br>    this.model = model;<br>  }<br><br>  start() {<br>    console.log(&quot;Vroom Vroom&quot;);<br>  }<br>}</pre><p>Well, when we declare <strong>class</strong> in JavaScript, we are actually creating a <strong>function with the constructor + prototype.</strong></p><p>Huh? What are you saying?</p><p><strong>In JavaScript, functions are callable objects</strong>, we can verify with:</p><pre>function test() {<br>  //<br>}<br><br>test.age = 23;<br>console.log(test.age); // 23</pre><p>So, the equivalent of the above <strong>class Car is just:</strong></p><pre>function CarFunc(name, model) {<br>  this.name = name;<br>  this.model = model;<br>}<br><br>function startFunc() {<br>  console.log(&quot;Vroom Vroom&quot;);<br>}<br><br>CarFunc.prototype.startFunc = startFunc;</pre><p>Yeah really, class is just a <strong>syntactic sugar for the constructor function + prototype</strong>. Under the hood, JavaScript is still using the function and prototype chaining.</p><p>Well, let’s understand about the <strong>function</strong> first.</p><p><strong>Functions</strong> are <strong>first class objects</strong>, this means functions can be assigned to variables, stored in data structures, passed as arguments to other functions, and returned from functions, enabling functional programming techniques like callbacks.</p><h4>Understanding the prototype chain</h4><p>Every object has internal property called <strong>[[Prototype]], which holds an internal reference </strong>to the other objects. When we access a method, it checks the object itself, if not found, check its [[Prototype]] and continue up the prototype chain and stops when <strong>null </strong>is reached.</p><pre>const vehicle = {<br>  start() {<br>    console.log(&quot;Vroom Vroom&quot;);<br>  },<br>};<br><br>const Maruti800 = Object.create(vehicle);<br><br>Maruti800.start(); // Vroom Vroom</pre><p>Here, <strong>Maruti800</strong> does not have <strong>start()</strong>, but JavaScript finds it in vehicle through the prototype chain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6757007e68ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Closure: Simplified]]></title>
            <link>https://medium.com/@iamsuman066/javascript-closure-simplified-0f53bfaa98c8?source=rss-480fb83e08cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f53bfaa98c8</guid>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[javascript-closure]]></category>
            <category><![CDATA[javascript-interview]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Suman Shrestha]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 04:20:03 GMT</pubDate>
            <atom:updated>2026-03-11T11:46:05.702Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8a0E0AqcbqeSyjLtEb92SA.jpeg" /><figcaption>cover image</figcaption></figure><p>If you’ve ever prepared for a JavaScript interview, you’ve probably come across the notorious concept called <strong>closures</strong>. It could feel daunting at first, but its pretty simple once we undercover its working mechanism.</p><p>In this article, we’ll break down how closure works in simple manner.</p><p><strong>Definition</strong>: Closure is created if the function remembers and continue to access its lexical context, even after the outer function has completed the execution.</p><p>Huh? What is the lexical context? You may ask,</p><p>In simple term, a closure is a function together with its lexical environment in which it was created.</p><pre>function outer(){<br>    let counter = 0;<br><br>    function inner(){<br>        counter++<br>        console.log(counter);<br>    }<br><br>    return inner<br>}<br><br>const test = outer(); <br>// test = function inner since outer returns the inner function;<br>// finish execution;<br><br>test(); <br>// now when we call the call test,<br>// what do you think happens, and what prints</pre><p>Here, once the outer function has been called, its execution context is created, and finishes execution with the return of the inner function.</p><p>Normally, l<strong>ocal variables</strong> should have been erased, right?</p><figure><img alt="gif for the execution context of the above program" src="https://cdn-images-1.medium.com/max/1024/1*uS3hu8AkC63LzuDobiTpoQ.gif" /><figcaption>Execution Flow/Context</figcaption></figure><p>The counter variable is in the outer, so after its execution, it should have been destroyed. Now, above execution flow suggest, when <strong>inner()</strong> or <strong>test()</strong> is invoked, it tries to increment the counter, <strong>counter ++</strong> so it checks its local variable, but there is no local variable counter in the inner function.</p><p>Huh?</p><p>It should have caused an issue right?</p><p>Well, it does not. The thing is, when a nested function <strong>uses a variable from the parent scope</strong>, JavaScript engine creates a <strong>Context object</strong>.</p><pre># Lexical Environment<br>Context {<br>  counter: 0<br>}</pre><p>Now the inner function gets a pointer to this context.</p><pre>child<br> └── [[Environment]] → Context { counter: 0 }</pre><p>So the inner function still have the reference to the context object, i.e. counter. So, counter++ updates the counter from context object.</p><pre>test<br>  ↓<br>inner function<br>  ↓<br>context object<br>  ↓<br>counter: 0 -&gt; counter++</pre><p>As long as <strong>inner </strong>exists, the <strong>context cannot be garbage collected</strong>. So even after the execution of outer, the counter variable still persists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q_j49pMQQp6Y6bmKyqjNcA.gif" /><figcaption>closure visualization</figcaption></figure><p>Now we understand, the closure is created when a function has access to its lexical context. We can say <strong>inner </strong>function closes over the counter.</p><p>Hope you liked this article, until then, rock on!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f53bfaa98c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication 101]]></title>
            <link>https://medium.com/@iamsuman066/authentication-101-99ef0d4d4f95?source=rss-480fb83e08cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/99ef0d4d4f95</guid>
            <category><![CDATA[sessions]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[csrf]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Suman Shrestha]]></dc:creator>
            <pubDate>Fri, 02 Jan 2026 06:28:21 GMT</pubDate>
            <atom:updated>2026-01-02T06:28:21.183Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fFfxuKwC6hFB5ItR" /><figcaption>Photo by <a href="https://unsplash.com/@edhardie?utm_source=medium&amp;utm_medium=referral">Ed Hardie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s discuss the authentication strategies used in majority of the web apps today. Beginning from the stateful and stateless authentication.</p><h3>Stateful authentication (Session based)</h3><p>Session/Cookie</p><p>Here, server handles the session by storing in either database or in memory store to remember you</p><p>Server manages the session by sending the cookie with session id to the frontend and followed by sending in subsequent requests.</p><p>Benefits</p><ol><li>Data lives on the server not exposed in the browser</li><li>server can enforce rules like expiration and logout centrally</li><li>Cookies are automatically sent by browsers with each request, so the client does not need special logic to attach tokens</li><li>Cookies can be flagged as HttpOnly and Secure to mitigate XSS and ensure they only travel over https adding security</li></ol><p>Cons</p><ol><li>Scaling can get tricky due to the nature of modern distributed systems like multiple databases in different edge locations</li><li>Cookies being automatically sent open the door to CSRF attacks if not protected -essentially, another site could impersonate user by sending their session cookie.</li></ol><h3>Stateless authentication (JWT)</h3><p>Json Web Token</p><p>when logged in the server verifies your credentials and then provide you with the client JWT instead of a session ID</p><p>The server signs the token often with the secret key to ensure it cannot be tampered with</p><p>The server does not store the token or any session in database thus, stateless authentication</p><p>Benefits</p><ol><li>Since there is no centralized session store, it is very scalable</li><li>They are great for APIs and mobile apps, for instance many modern REST/GraphQL APIs uses JWTs so that clients like SPA or mobile app can authenticate without relying on browser cookies</li></ol><p>Cons</p><ol><li>Security and revocations are the biggest concerns, if a JWT is stolen an attacker can use it until it expires, the server has no built in way to nullify an individual token immediately, unlike a session where you could delete a record in a database.</li><li>let’s say if the user permission change, the JWT does not know unless invalidated or revoked or reissued</li><li>Storing on local storage, they could be stolen via XSS, if stored in cookies they become vulnerable to CSRF</li></ol><h3>Cross Site Request Forgery (CSRF)</h3><p>It is an attack that forces an end user to execute unwanted actions on a web application in which they are currently authenticated.</p><p>By sending links, the attacker may trick the users of a web application into executing actions of the attackers choosing.</p><p>If the victim is a normal user, a successful CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address</p><p>CSRF attack functionality that causes state change on the server, such as changing the victims email address or password, or purchasing something.</p><p>Reasons</p><ol><li>Forcing the victim to retrieve data does not benefit an attacker because attacker does not receive the response, the victim does, thus they do state changing requests.</li><li>Vulnerable site itself can be injected with IMG or IFRAME tag in a field that accepts HTML or by a more complex cross site scripting attack</li></ol><h4>Prevention Measures that do not work</h4><ol><li><strong>Using a secret cookie:</strong> All cookies are submitted with every request, regardless of whether or not the end user was tricked into submitting the request</li><li><strong>HTTPS: </strong>It is the prerequisite for preventative measures, but itself does nothing to defend against CSRF</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99ef0d4d4f95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Form with React Hook Form, ShadCN and Next JS]]></title>
            <link>https://medium.com/@iamsuman066/dynamic-form-with-react-hook-form-shadcn-and-next-js-63402ebb3e42?source=rss-480fb83e08cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/63402ebb3e42</guid>
            <category><![CDATA[dynamic-form]]></category>
            <category><![CDATA[shadcn]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Suman Shrestha]]></dc:creator>
            <pubDate>Tue, 09 Dec 2025 05:37:35 GMT</pubDate>
            <atom:updated>2025-12-09T05:37:35.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pXXbLGd-4vGflXmP" /><figcaption>Photo by <a href="https://unsplash.com/@danielleone?utm_source=medium&amp;utm_medium=referral">Daniel Leone</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello buddies, today we will learn how we can make dynamic form with react hook form, shadCN and Next JS.</p><p>In this demo, we will be creating experience section of a resume maker, since user can add multiple experiences, we cannot add static fields like personal details. Thus, in this article we will use dynamic form, where user can add multiple records in the form. Now, let’s begin.</p><blockquote>GitHub <a href="https://github.com/heySuman/resume-creator"><strong>link </strong></a>| Live Preview <a href="https://resume-creator-five.vercel.app/create/1/experiences"><strong>here</strong></a></blockquote><h3>1. Setup Next JS and Shadcn</h3><pre>pnpm create next-app@latest my-app --yes</pre><p>This will install next js, now let’s setup shadcn.</p><pre>pnpm dlx shadcn@latest init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OeOmYWdJ0amHrHv0-hxnPA.png" /><figcaption>Adding shadcn to Next JS</figcaption></figure><p>Now we are ready to add components to our projects. We will be using following components from the library.</p><pre>pnpm dlx shadcn@latest add button field input accordion textarea popover calendar</pre><h3>2. Add React Hook Form and Zod</h3><p>We will be using react hook form for form validation and Zod for creating and validating schemas.</p><pre>pnpm add react-hook-form zod @hookform/resolvers</pre><h3>3. Creating Schema for Dynamic Form</h3><pre>// schemas/employment.ts<br><br>import { z } from &quot;zod&quot;<br><br>const employmentSchema = z.object({<br>    jobTitle: z.string(),<br>    employer: z.string(),<br>    startDate: z.date().nullable(),<br>    endDate: z.date().nullable(),<br>    city: z.string().nullable(),<br>    description: z.string().nullable()<br>})<br><br>export { employmentSchema }</pre><p>From the above zod schema for react hook form, we use <strong>useForm</strong> to create the form validation for our dynamic form. React Hook Form provide powerful methods and hooks with better type-safety and easier inference.</p><ol><li>useForm(): hook to validate form</li><li>useFieldArray(): this hook enables us for the field array for dynamic form.</li></ol><pre>const formSchema = z.object({<br>        experiences: z.array(employmentSchema)<br>    })<br><br>    type FormSchema = z.infer&lt;typeof formSchema&gt;;<br><br>    const form = useForm&lt;FormSchema&gt;({<br>        defaultValues: {<br>            experiences: [{<br>                jobTitle: &quot;&quot;,<br>                city: &quot;&quot;,<br>                description: &quot;&quot;,<br>                employer: &quot;&quot;,<br>                endDate: null,<br>                startDate: null<br>            }]<br>        },<br>        resolver: zodResolver(formSchema)<br>    })<br><br>    const { append, remove, fields } = useFieldArray({<br>        control: form.control,<br>        name: &quot;experiences&quot;<br>    })<br><br>    const handleAddExperience = () =&gt; append({<br>        jobTitle: &quot;&quot;,<br>        city: &quot;&quot;,<br>        description: &quot;&quot;,<br>        employer: &quot;&quot;,<br>        endDate: null,<br>        startDate: null<br>    })<br><br>    const handleRemoveExperience = (index: number) =&gt; remove(index);</pre><p>useForm helps us to validate our form against the zod schema, where we put the default values and zodResolver for the react hook form, you may use other validation library instead of zod, like yup and joi.</p><p>useFieldArray provides append, remove, prepend, replace methods for the dynamic fields, which is very intuitive as user adds we append, if user delete experience we can use remove method.</p><blockquote>You may refer the documentation <a href="https://react-hook-form.com/docs/usefieldarray"><strong>here</strong></a>.</blockquote><p>Here is the full implementation with collapsible Accordion compoenent from Shadcn that is intuitive and easier to visualize.</p><pre>&quot;use client&quot;<br><br>import z from &quot;zod&quot;<br>import { Activity } from &quot;react&quot;<br>import { Input } from &quot;@/components/ui/input&quot;<br>import { Button } from &quot;@/components/ui/button&quot;<br>import { Textarea } from &quot;@/components/ui/textarea&quot;<br>import { zodResolver } from &quot;@hookform/resolvers/zod&quot;<br>import { DatePicker } from &quot;@/components/ui/date-picker&quot;<br>import { GripVertical, Plus, Trash2 } from &quot;lucide-react&quot;<br>import { employmentSchema } from &quot;@/schemas/professional-details&quot;<br>import { Field, FieldError, FieldGroup, FieldLabel } from &quot;@/components/ui/field&quot;<br>import { Controller, FormProvider, useFieldArray, useForm } from &quot;react-hook-form&quot;<br>import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from &quot;@/components/ui/accordion&quot;<br><br>export default function Experience() {<br><br>    const formSchema = z.object({<br>        experiences: z.array(employmentSchema)<br>    })<br><br>    type FormSchema = z.infer&lt;typeof formSchema&gt;;<br><br>    const form = useForm&lt;FormSchema&gt;({<br>        defaultValues: {<br>            experiences: [{<br>                jobTitle: &quot;&quot;,<br>                city: &quot;&quot;,<br>                description: &quot;&quot;,<br>                employer: &quot;&quot;,<br>                endDate: null,<br>                startDate: null<br>            }]<br>        },<br>        resolver: zodResolver(formSchema)<br>    })<br><br>    const { append, remove, fields } = useFieldArray({<br>        control: form.control,<br>        name: &quot;experiences&quot;<br>    })<br><br>    const handleAddExperience = () =&gt; append({<br>        jobTitle: &quot;&quot;,<br>        city: &quot;&quot;,<br>        description: &quot;&quot;,<br>        employer: &quot;&quot;,<br>        endDate: null,<br>        startDate: null<br>    })<br><br>    const handleRemoveExperience = (index: number) =&gt; remove(index);<br><br>    return (<br>        &lt;div className=&quot;max-w-md p-5&quot;&gt;<br><br>            &lt;div className=&quot;flex items-center justify-between&quot;&gt;<br>                &lt;h1 className=&quot;text-2xl font-bold&quot;&gt;Experiences&lt;/h1&gt;<br>                &lt;Button size={&quot;icon-sm&quot;} onClick={handleAddExperience}&gt;&lt;Plus /&gt;&lt;/Button&gt;<br>            &lt;/div&gt;<br><br>            &lt;FormProvider {...form}&gt;<br>                &lt;form&gt;<br>                    &lt;Accordion type=&quot;single&quot; collapsible&gt;<br>                        {<br>                            fields.map((field, index) =&gt; (<br>                                &lt;AccordionItem value={`educations.${index}`} key={field.id}&gt;<br>                                    &lt;AccordionTrigger&gt;&lt;GripVertical /&gt;{form.watch(`experiences.${index}.employer`) || &quot;(Not Specified)&quot;}&lt;/AccordionTrigger&gt;<br><br>                                    &lt;AccordionContent&gt;<br><br>                                        &lt;FieldGroup&gt;<br>                                            &lt;Controller<br>                                                control={form.control}<br>                                                name={`experiences.${index}.jobTitle`}<br>                                                render={({ field, fieldState }) =&gt; (<br>                                                    &lt;Field data-invalid={fieldState.invalid}&gt;<br>                                                        &lt;FieldLabel htmlFor=&quot;jobTitle&quot;&gt;Job Title&lt;/FieldLabel&gt;<br>                                                        &lt;Input {...field} placeholder=&quot;Enter your job title&quot; aria-invalid={fieldState.invalid} /&gt;<br><br>                                                        &lt;Activity mode={fieldState.invalid ? &quot;visible&quot; : &quot;hidden&quot;}&gt;<br>                                                            &lt;FieldError errors={[fieldState.error]} /&gt;<br>                                                        &lt;/Activity&gt;<br>                                                    &lt;/Field&gt;<br>                                                )}<br>                                            /&gt;<br><br>                                            &lt;Controller<br>                                                control={form.control}<br>                                                name={`experiences.${index}.employer`}<br>                                                render={({ field, fieldState }) =&gt; (<br>                                                    &lt;Field data-invalid={fieldState.invalid}&gt;<br>                                                        &lt;FieldLabel htmlFor=&quot;employer&quot;&gt;Employer Name&lt;/FieldLabel&gt;<br>                                                        &lt;Input {...field} placeholder=&quot;Enter your employer name&quot; aria-invalid={fieldState.invalid} /&gt;<br><br>                                                        &lt;Activity mode={fieldState.invalid ? &quot;visible&quot; : &quot;hidden&quot;}&gt;<br>                                                            &lt;FieldError errors={[fieldState.error]} /&gt;<br>                                                        &lt;/Activity&gt;<br>                                                    &lt;/Field&gt;<br>                                                )}<br>                                            /&gt;<br><br>                                            &lt;div className=&quot;flex flex-col sm:flex-row sm:gap-2 items-center&quot;&gt;<br><br><br>                                                &lt;Controller<br>                                                    control={form.control}<br>                                                    name={`experiences.${index}.startDate`}<br>                                                    render={({ field, fieldState }) =&gt; (<br>                                                        &lt;Field data-invalid={fieldState.invalid}&gt;<br>                                                            &lt;FieldLabel htmlFor=&quot;startDate&quot;&gt;Start Date&lt;/FieldLabel&gt;<br>                                                            &lt;DatePicker {...field} aria-invalid={fieldState.invalid} /&gt;<br><br>                                                            &lt;Activity mode={fieldState.invalid ? &quot;visible&quot; : &quot;hidden&quot;}&gt;<br>                                                                &lt;FieldError errors={[fieldState.error]} /&gt;<br>                                                            &lt;/Activity&gt;<br>                                                        &lt;/Field&gt;<br>                                                    )}<br>                                                /&gt;<br><br>                                                &lt;Controller<br>                                                    control={form.control}<br>                                                    name={`experiences.${index}.endDate`}<br>                                                    render={({ field, fieldState }) =&gt; (<br>                                                        &lt;Field data-invalid={fieldState.invalid}&gt;<br>                                                            &lt;FieldLabel htmlFor=&quot;endDate&quot;&gt;End Date (optional)&lt;/FieldLabel&gt;<br>                                                            &lt;DatePicker<br>                                                                {...field}<br>                                                                value={field.value}<br>                                                                aria-invalid={fieldState.invalid} /&gt;<br><br>                                                            &lt;Activity mode={fieldState.invalid ? &quot;visible&quot; : &quot;hidden&quot;}&gt;<br>                                                                &lt;FieldError errors={[fieldState.error]} /&gt;<br>                                                            &lt;/Activity&gt;<br>                                                        &lt;/Field&gt;<br>                                                    )}<br>                                                /&gt;<br>                                            &lt;/div&gt;<br><br><br><br>                                            &lt;Controller<br>                                                control={form.control}<br>                                                name={`experiences.${index}.city`}<br>                                                render={({ field, fieldState }) =&gt; (<br>                                                    &lt;Field data-invalid={fieldState.invalid}&gt;<br>                                                        &lt;FieldLabel htmlFor=&quot;city&quot;&gt;City&lt;/FieldLabel&gt;<br>                                                        &lt;Input {...field} value={field.value ?? &quot;&quot;} placeholder=&quot;Enter your city&quot; aria-invalid={fieldState.invalid} /&gt;<br><br>                                                        &lt;Activity mode={fieldState.invalid ? &quot;visible&quot; : &quot;hidden&quot;}&gt;<br>                                                            &lt;FieldError errors={[fieldState.error]} /&gt;<br>                                                        &lt;/Activity&gt;<br>                                                    &lt;/Field&gt;<br>                                                )}<br>                                            /&gt;<br><br>                                            &lt;Controller<br>                                                control={form.control}<br>                                                name={`experiences.${index}.description`}<br>                                                render={({ field, fieldState }) =&gt; (<br>                                                    &lt;Field data-invalid={fieldState.invalid}&gt;<br>                                                        &lt;FieldLabel htmlFor=&quot;description&quot;&gt;Description&lt;/FieldLabel&gt;<br>                                                        &lt;Textarea {...field} value={field.value ?? &quot;&quot;} placeholder=&quot;Describe what you learnt there&quot; aria-invalid={fieldState.invalid} /&gt;<br><br>                                                        &lt;Activity mode={fieldState.invalid ? &quot;visible&quot; : &quot;hidden&quot;}&gt;<br>                                                            &lt;FieldError errors={[fieldState.error]} /&gt;<br>                                                        &lt;/Activity&gt;<br>                                                    &lt;/Field&gt;<br>                                                )}<br>                                            /&gt;<br><br>                                            &lt;Button onClick={() =&gt; handleRemoveExperience(index)} size={&quot;lg&quot;} variant={&quot;outline&quot;} className=&quot;max-w-fit text-destructive&quot;&gt;<br>                                                Remove &lt;Trash2 /&gt;<br>                                            &lt;/Button&gt;<br>                                        &lt;/FieldGroup&gt;<br>                                    &lt;/AccordionContent&gt;<br>                                &lt;/AccordionItem&gt;<br>                            ))<br>                        }<br>                    &lt;/Accordion&gt;<br>                &lt;/form&gt;<br>            &lt;/FormProvider&gt;<br>        &lt;/div&gt;<br>    )<br>}</pre><p>It’s easy, right? we use field component of the shadcn alongside the react hook form for each field in the form. Here is what it looks like currently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*x5ff4M4lXyP87z57KaQL7g.png" /><figcaption>Final Result</figcaption></figure><p>By this way, we can make a dynamic form, you can get code <a href="https://github.com/heySuman/resume-creator"><strong>here</strong></a>. And live preview is also available <a href="https://resume-creator-five.vercel.app/create/1/experiences"><strong>here</strong></a>.</p><p>See you buddies!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63402ebb3e42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy Multi-Step Form with NextJs, Shadcn and React Hook Form]]></title>
            <link>https://medium.com/@iamsuman066/easy-multi-step-form-with-nextjs-shadcn-and-react-hook-form-1138200fb9e3?source=rss-480fb83e08cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/1138200fb9e3</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react-hook-form]]></category>
            <category><![CDATA[multi-step-form]]></category>
            <category><![CDATA[shadcn]]></category>
            <dc:creator><![CDATA[Suman Shrestha]]></dc:creator>
            <pubDate>Thu, 06 Nov 2025 17:51:45 GMT</pubDate>
            <atom:updated>2025-11-06T17:51:45.255Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ck2OL4AhPWWqajln" /><figcaption>Photo by <a href="https://unsplash.com/@sepoys?utm_source=medium&amp;utm_medium=referral">Rohit Tandon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Forms are complex, multi-step forms are even more complex. In this article, we will learn how we can use React Hook Form and Shadcn to create easy multi step form.</p><p><em>Live Example </em><a href="https://multi-step-form-example.vercel.app/"><strong><em>here</em></strong></a><em>. Code</em><strong><em> </em></strong><a href="https://github.com/heySuman/multi-step-form-example"><strong><em>here</em></strong></a><strong><em>.</em></strong></p><blockquote>Requisites: Basic knowledge of React (version 19.2) and state management.</blockquote><p>Let’s begin simple and straightforward. Create a next js project and install Shadcn for the prebuilt components.</p><pre>npx create-next-app@latest multi-step-form<br>npx shadcn@latest init</pre><p>Install react hook form and zod for form validation.</p><pre> npm i react-hook-form zod @hookform/resolvers<br> npx shadcn@latest add card input button field sonner</pre><p>Once you have installed these, open code editor of your choice and let’s begin.</p><p>Let’s create a multi-step form for a resume maker application, as form gets too large to take input about personal, educational and experiences, it could be harming your user experience.</p><p>Listing the details we require to create a resume,</p><ol><li>Personal Details</li></ol><ul><li>Name</li><li>Phone</li><li>Address</li><li>Age</li></ul><p>2. Educational Background</p><ul><li>Degree</li><li>Institute</li><li>Start Date</li><li>End Date</li></ul><p>In this app we will only focus on these two aspects of a resume to keep it simple.</p><p>In your app folder, open page.tsx</p><pre>// Personal Schema<br>const PersonalSchema = z.object({<br>  name: z.string().min(1, { error: &quot;Name is required.&quot; }),<br>  phone: z.string().min(1, { error: &quot;Contact is required.&quot; }),<br>  address: z.string().min(1, { error: &quot;Address is required.&quot; }),<br>  age: z.string().min(1, { error: &quot;Age is required.&quot; }),<br>})<br><br>// Education Schema<br>const EducationalSchema = z.object({<br>  degree: z.string().min(1, { error: &quot;Name is required.&quot; }),<br>  institute: z.string().min(1, { error: &quot;Name is required.&quot; }),<br>  startDate: z.date(),<br>  endDate: z.date().optional(),<br>})<br><br>// Combining Personal and Education Schema <br>// under single Schema for our multi-step form <br>const resumeSchema = PersonalSchema.extend(EducationalSchema.shape)</pre><p>We create zod schema for validating our form.</p><p>We use React Hook Form for the form state management, and we need to use the hook from react-hook-form <strong>useForm </strong>to validate and for initial values.</p><pre>&quot;use client&quot;<br>import * as z from &quot;zod&quot;<br>import {<br>  Card,<br>  CardContent, <br>  CardDescription,<br>  CardHeader,<br>  CardTitle } from &quot;@/components/ui/card&quot;;<br>import { useForm } from &quot;react-hook-form&quot;;<br>import { zodResolver } from &quot;@hookform/resolvers/zod&quot;;<br><br>// Personal Schema<br>const PersonalSchema = z.object({<br>  name: z.string().min(1, { error: &quot;Name is required.&quot; }),<br>  phone: z.string().min(1, { error: &quot;Contact is required.&quot; }),<br>  address: z.string().min(1, { error: &quot;Address is required.&quot; }),<br>  age: z.number().min(10, { error: &quot;Age is required.&quot; }),<br>})<br><br>// Education Schema<br>const EducationalSchema = z.object({<br>  degree: z.string().min(1, { error: &quot;Name is required.&quot; }),<br>  institute: z.string().min(1, { error: &quot;Name is required.&quot; }),<br>  startDate: z.date(),<br>  endDate: z.date().optional(),<br>})<br><br>// Combining Personal and Education Schema<br>// under single Schema for our form<br> <br>const resumeSchema = PersonalSchema.extend(EducationalSchema.shape)<br><br>export default function Page() {<br>  const form = useForm&lt;z.infer&lt;typeof resumeSchema&gt;&gt;(<br>    {<br>      resolver: zodResolver(resumeSchema),<br>      defaultValues: {<br>        name: &quot;&quot;,<br>        phone: &quot;&quot;,<br>        address:&quot;&quot;,<br>        age: undefined,<br>        degree: &quot;&quot;,<br>        institute: &quot;&quot;,<br>        startDate: undefined,<br>        endDate: undefined<br>      }<br>    }<br>  )<br>  <br>  return (<br>    &lt;Card className=&quot;w-full sm:max-w-md my-10 mx-auto&quot;&gt;<br>      &lt;CardHeader&gt;<br>        &lt;CardTitle&gt;Resume Builder&lt;/CardTitle&gt;<br>        &lt;CardDescription&gt;<br>            Enter your details to create a resume.<br>        &lt;/CardDescription&gt;<br>      &lt;/CardHeader&gt;<br><br>      &lt;CardContent&gt;<br>        {/* Here will be our form */}<br>      &lt;/CardContent&gt;<br>    &lt;/Card&gt;<br>  )<br>}</pre><p>Now it&#39;s turn of creating form.</p><pre>&quot;use client&quot;<br>import * as z from &quot;zod&quot;<br>import {<br>  Card,<br>  CardContent,<br>  CardDescription,<br>  CardHeader,<br>  CardTitle<br>} from &quot;@/components/ui/card&quot;;<br>import { Input } from &quot;@/components/ui/input&quot;;<br>import { Controller, useForm } from &quot;react-hook-form&quot;;<br>import { zodResolver } from &quot;@hookform/resolvers/zod&quot;;<br>import { Field, FieldError, FieldGroup, FieldLabel } from &quot;@/components/ui/field&quot;;<br><br>// Personal Schema<br>const PersonalSchema = z.object({<br>  name: z.string().min(1, { error: &quot;Name is required.&quot; }),<br>  phone: z.string().min(1, { error: &quot;Contact is required.&quot; }),<br>  address: z.string().min(1, { error: &quot;Address is required.&quot; }),<br>  age: z.string().min(1, { error: &quot;Age is required.&quot; }),<br>})<br><br>// Education Schema<br>const EducationalSchema = z.object({<br>  degree: z.string().min(1, { error: &quot;Name is required.&quot; }),<br>  institute: z.string().min(1, { error: &quot;Name is required.&quot; }),<br>  startDate: z.coerce.date().optional().nullable(),<br>  endDate: z.coerce.date().optional().nullable(),<br>})<br><br>// Combining Personal and Education Schema under single Schema for our form <br>const resumeSchema = PersonalSchema.extend(EducationalSchema.shape)<br><br>export default function Page() {<br>  const form = useForm(<br>    {<br>      resolver: zodResolver(resumeSchema),<br>      defaultValues: {<br>        name: &quot;&quot;,<br>        phone: &quot;&quot;,<br>        address: &quot;&quot;,<br>        age: &quot;&quot;,<br>        degree: &quot;&quot;,<br>        institute: &quot;&quot;,<br>        startDate: null,<br>        endDate: null<br>      }<br>    }<br>  )<br><br>  return (<br>    &lt;Card className=&quot;w-full sm:max-w-md my-10 mx-auto&quot;&gt;<br>      &lt;CardHeader&gt;<br>        &lt;CardTitle&gt;Resume Builder&lt;/CardTitle&gt;<br>        &lt;CardDescription&gt;Enter your details to create a resume.&lt;/CardDescription&gt;<br>      &lt;/CardHeader&gt;<br><br>      &lt;CardContent&gt;<br>        &lt;form&gt;<br>          &lt;FieldGroup&gt;<br><br>            {/* Personal */}<br>            &lt;h2 className=&quot;text-md font-medium&quot;&gt;Personal Detail&lt;/h2&gt;<br><br>            &lt;Controller<br>              name=&quot;name&quot;<br>              control={form.control}<br>              render={({ field, fieldState }) =&gt; (<br>                &lt;Field&gt;<br>                  &lt;FieldLabel htmlFor=&quot;name&quot;&gt;<br>                    Name<br>                  &lt;/FieldLabel&gt;<br>                  &lt;Input<br>                    {...field}<br>                    placeholder=&quot;e.g. John Doe&quot;<br>                  /&gt;<br><br>                  {fieldState.invalid &amp;&amp; (<br>                    &lt;FieldError errors={[fieldState.error]} /&gt;<br>                  )}<br>                &lt;/Field&gt;<br>              )}<br>            /&gt;<br><br>            &lt;Controller<br>              name=&quot;phone&quot;<br>              control={form.control}<br>              render={({ field, fieldState }) =&gt; (<br>                &lt;Field&gt;<br>                  &lt;FieldLabel htmlFor=&quot;phone&quot;&gt;<br>                    Phone<br>                  &lt;/FieldLabel&gt;<br>                  &lt;Input<br>                    {...field}<br>                    placeholder=&quot;e.g. 0123456789&quot;<br>                  /&gt;<br><br>                  {fieldState.invalid &amp;&amp; (<br>                    &lt;FieldError errors={[fieldState.error]} /&gt;<br>                  )}<br>                &lt;/Field&gt;<br>              )}<br>            /&gt;<br><br>            &lt;Controller<br>              name=&quot;address&quot;<br>              control={form.control}<br>              render={({ field, fieldState }) =&gt; (<br>                &lt;Field&gt;<br>                  &lt;FieldLabel htmlFor=&quot;address&quot;&gt;<br>                    Address<br>                  &lt;/FieldLabel&gt;<br>                  &lt;Input<br>                    {...field}<br>                    placeholder=&quot;e.g. Melbourne, Australia&quot;<br>                  /&gt;<br><br>                  {fieldState.invalid &amp;&amp; (<br>                    &lt;FieldError errors={[fieldState.error]} /&gt;<br>                  )}<br>                &lt;/Field&gt;<br>              )}<br>            /&gt;<br>            &lt;Controller<br>              name=&quot;age&quot;<br>              control={form.control}<br>              render={({ field, fieldState }) =&gt; (<br>                &lt;Field&gt;<br>                  &lt;FieldLabel htmlFor=&quot;age&quot;&gt;<br>                    Age<br>                  &lt;/FieldLabel&gt;<br>                  &lt;Input<br>                    {...field}<br>                    placeholder=&quot;e.g. 8&quot;<br>                  /&gt;<br><br>                  {fieldState.invalid &amp;&amp; (<br>                    &lt;FieldError errors={[fieldState.error]} /&gt;<br>                  )}<br>                &lt;/Field&gt;<br>              )}<br>            /&gt;<br><br>            {/* Educational */}<br>            &lt;h2 className=&quot;text-md font-medium&quot;&gt;Educational Detail&lt;/h2&gt;<br>            &lt;Controller<br>              name=&quot;degree&quot;<br>              control={form.control}<br>              render={({ field, fieldState }) =&gt; (<br>                &lt;Field&gt;<br>                  &lt;FieldLabel htmlFor=&quot;degree&quot;&gt;<br>                    Degree<br>                  &lt;/FieldLabel&gt;<br>                  &lt;Input<br>                    {...field}<br>                    placeholder=&quot;e.g. Bachelor in Accounting&quot;<br>                  /&gt;<br><br>                  {fieldState.invalid &amp;&amp; (<br>                    &lt;FieldError errors={[fieldState.error]} /&gt;<br>                  )}<br>                &lt;/Field&gt;<br>              )}<br>            /&gt;<br><br>            &lt;Controller<br>              name=&quot;institute&quot;<br>              control={form.control}<br>              render={({ field, fieldState }) =&gt; (<br>                &lt;Field&gt;<br>                  &lt;FieldLabel htmlFor=&quot;institute&quot;&gt;<br>                    Institute<br>                  &lt;/FieldLabel&gt;<br>                  &lt;Input<br>                    {...field}<br>                    placeholder=&quot;e.g. Oxford University&quot;<br>                  /&gt;<br><br>                  {fieldState.invalid &amp;&amp; (<br>                    &lt;FieldError errors={[fieldState.error]} /&gt;<br>                  )}<br>                &lt;/Field&gt;<br>              )}<br>            /&gt;<br><br>            &lt;Controller<br>              name=&quot;startDate&quot;<br>              control={form.control}<br>              render={({ field, fieldState }) =&gt; (<br>                &lt;Field&gt;<br>                  &lt;FieldLabel htmlFor=&quot;startDate&quot;&gt;<br>                    Start Date<br>                  &lt;/FieldLabel&gt;<br>                  &lt;Input<br>                    type=&quot;date&quot;<br>                    value={field.value ? (field.value as Date).toISOString().slice(0, 10) : &quot;&quot;}<br>                    onChange={(e) =&gt; field.onChange(e.target.value ? new Date(e.target.value) : null)}<br>                  /&gt;<br><br>                  {fieldState.invalid &amp;&amp; (<br>                    &lt;FieldError errors={[fieldState.error]} /&gt;<br>                  )}<br>                &lt;/Field&gt;<br>              )}<br>            /&gt;<br><br>            &lt;Controller<br>              name=&quot;endDate&quot;<br>              control={form.control}<br>              render={({ field, fieldState }) =&gt; (<br>                &lt;Field&gt;<br>                  &lt;FieldLabel htmlFor=&quot;endDate&quot;&gt;<br>                    End Date<br>                  &lt;/FieldLabel&gt;<br>                  &lt;Input<br>                    type=&quot;date&quot;<br>                    value={field.value ? (field.value as Date).toISOString().slice(0, 10) : &quot;&quot;}<br>                    onChange={(e) =&gt; field.onChange(e.target.value ? new Date(e.target.value) : null)}<br>                  /&gt;<br><br>                  {fieldState.invalid &amp;&amp; (<br>                    &lt;FieldError errors={[fieldState.error]} /&gt;<br>                  )}<br>                &lt;/Field&gt;<br>              )}<br>            /&gt;<br><br>          &lt;/FieldGroup&gt;<br><br>        &lt;/form&gt;<br>      &lt;/CardContent&gt;<br>    &lt;/Card&gt;<br>  )<br>}</pre><p>This code corresponds to overflowing fields as we can see in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*Nf3Ha4XZ1UCxUC61w-nLww.png" /><figcaption>Overflowing Form</figcaption></figure><p>When we see form with too much input, it makes us not want to fill it, thus we need to make it manageable, step by step.</p><p>Now we need to make multi-step form, for personal and educational details.</p><p>To make the state persistent, we will make use of Activity Component from React 19.2. Activity can be used to persist the state while toggling the visibility of the component.</p><pre>&lt;Activity mode = {&quot;visible&quot; || &quot;hidden&quot;}&gt;<br>  &lt;/YourComponent&gt;<br>&lt;/Activity&gt;</pre><p>SO here, for our multi-step form we will use activity component to hide fields that are not in current step.</p><p>Here is a final code:</p><pre>&quot;use client&quot;<br>import * as z from &quot;zod&quot;<br>import {<br>  Card,<br>  CardContent,<br>  CardDescription,<br>  CardFooter,<br>  CardHeader,<br>  CardTitle<br>} from &quot;@/components/ui/card&quot;;<br>import { Input } from &quot;@/components/ui/input&quot;;<br>import { Controller, useForm } from &quot;react-hook-form&quot;;<br>import { zodResolver } from &quot;@hookform/resolvers/zod&quot;;<br>import { Field, FieldError, FieldGroup, FieldLabel } from &quot;@/components/ui/field&quot;;<br>import { Activity, useState } from &quot;react&quot;;<br>import { Button } from &quot;@/components/ui/button&quot;;<br>import { toast, Toaster } from &quot;sonner&quot;;<br><br>// Personal Schema<br>const PersonalSchema = z.object({<br>  name: z.string().min(1, { error: &quot;Name is required.&quot; }),<br>  phone: z.string().min(1, { error: &quot;Contact is required.&quot; }),<br>  address: z.string().min(1, { error: &quot;Address is required.&quot; }),<br>  age: z.string().min(1, { error: &quot;Age is required.&quot; }),<br>})<br><br>// Education Schema<br>const EducationalSchema = z.object({<br>  degree: z.string().min(1, { error: &quot;Degree is required.&quot; }),<br>  institute: z.string().min(1, { error: &quot;Institute is required.&quot; }),<br>  startDate: z.coerce.date().optional().nullable(),<br>  endDate: z.coerce.date().optional().nullable(),<br>})<br><br>// Combining Personal and Education Schema under single Schema for our form <br>const resumeSchema = PersonalSchema.extend(EducationalSchema.shape)<br><br>export default function Page() {<br><br>  const [activeStep, setActiveStep] = useState(0)<br>  const steps = [<br>    { name: &quot;personal&quot;, schema: PersonalSchema },<br>    { name: &quot;educational&quot;, schema: EducationalSchema },<br>  ] as const;<br><br>  const currentStep = steps[activeStep].name<br><br>  const form = useForm({<br>    resolver: zodResolver(resumeSchema),<br>    defaultValues: {<br>      name: &quot;&quot;,<br>      phone: &quot;&quot;,<br>      address: &quot;&quot;,<br>      age: &quot;&quot;,<br>      degree: &quot;&quot;,<br>      institute: &quot;&quot;,<br>      startDate: null,<br>      endDate: null<br>    }<br>  })<br><br>  // from shadcn example of form with react hook form<br>  // link: https://ui.shadcn.com/docs/forms/react-hook-form<br>  function onSubmit(data: z.infer&lt;typeof resumeSchema&gt;) {<br>    toast(&quot;You submitted the following values:&quot;, {<br>      description: (<br>        &lt;pre className=&quot;bg-code text-code-foreground mt-2 w-[320px] overflow-x-auto rounded-md p-4&quot;&gt;<br>          &lt;code&gt;{JSON.stringify(data, null, 2)}&lt;/code&gt;<br>        &lt;/pre&gt;<br>      ),<br>      position: &quot;bottom-right&quot;,<br>      classNames: {<br>        content: &quot;flex flex-col gap-2&quot;,<br>      },<br>      style: {<br>        &quot;--border-radius&quot;: &quot;calc(var(--radius)  + 4px)&quot;,<br>      } as React.CSSProperties,<br>    })<br>  }<br><br>  return (<br>    &lt;Card className=&quot;w-full sm:max-w-md my-10 mx-auto&quot;&gt;<br>      &lt;CardHeader&gt;<br>        &lt;CardTitle&gt;Resume Builder&lt;/CardTitle&gt;<br>        &lt;CardDescription&gt;Enter your details to create a resume.&lt;/CardDescription&gt;<br>      &lt;/CardHeader&gt;<br><br>      &lt;CardContent&gt;<br>        &lt;form id=&quot;resume-form&quot; onSubmit={form.handleSubmit(onSubmit)}&gt;<br>          &lt;FieldGroup&gt;<br><br>            &lt;Activity mode={currentStep === &quot;personal&quot; ? &quot;visible&quot; : &quot;hidden&quot;}&gt;<br><br>              {/* Personal */}<br>              &lt;h2 className=&quot;text-md font-medium&quot;&gt;Personal Detail&lt;/h2&gt;<br><br>              &lt;Controller<br>                name=&quot;name&quot;<br>                control={form.control}<br>                render={({ field, fieldState }) =&gt; (<br>                  &lt;Field&gt;<br>                    &lt;FieldLabel htmlFor=&quot;name&quot;&gt;<br>                      Name<br>                    &lt;/FieldLabel&gt;<br>                    &lt;Input<br>                      {...field}<br>                      placeholder=&quot;e.g. John Doe&quot;<br>                    /&gt;<br>                    {fieldState.invalid &amp;&amp; (&lt;FieldError errors={[fieldState.error]} /&gt;)}<br>                  &lt;/Field&gt;<br>                )}<br>              /&gt;<br><br>              &lt;Controller<br>                name=&quot;phone&quot;<br>                control={form.control}<br>                render={({ field, fieldState }) =&gt; (<br>                  &lt;Field&gt;<br>                    &lt;FieldLabel htmlFor=&quot;phone&quot;&gt;<br>                      Phone<br>                    &lt;/FieldLabel&gt;<br>                    &lt;Input<br>                      {...field}<br>                      placeholder=&quot;e.g. 0123456789&quot;<br>                    /&gt;<br>                    {fieldState.invalid &amp;&amp; (&lt;FieldError errors={[fieldState.error]} /&gt;)}<br>                  &lt;/Field&gt;<br>                )}<br>              /&gt;<br><br>              &lt;Controller<br>                name=&quot;address&quot;<br>                control={form.control}<br>                render={({ field, fieldState }) =&gt; (<br>                  &lt;Field&gt;<br>                    &lt;FieldLabel htmlFor=&quot;address&quot;&gt;<br>                      Address<br>                    &lt;/FieldLabel&gt;<br>                    &lt;Input<br>                      {...field}<br>                      placeholder=&quot;e.g. Melbourne, Australia&quot;<br>                    /&gt;<br>                    {fieldState.invalid &amp;&amp; (&lt;FieldError errors={[fieldState.error]} /&gt;)}<br>                  &lt;/Field&gt;<br>                )}<br>              /&gt;<br>              &lt;Controller<br>                name=&quot;age&quot;<br>                control={form.control}<br>                render={({ field, fieldState }) =&gt; (<br>                  &lt;Field&gt;<br>                    &lt;FieldLabel htmlFor=&quot;age&quot;&gt;<br>                      Age<br>                    &lt;/FieldLabel&gt;<br>                    &lt;Input<br>                      {...field}<br>                      placeholder=&quot;e.g. 8&quot;<br>                    /&gt;<br>                    {fieldState.invalid &amp;&amp; (&lt;FieldError errors={[fieldState.error]} /&gt;)}<br>                  &lt;/Field&gt;<br>                )}<br>              /&gt;<br>            &lt;/Activity&gt;<br><br>            {/* Educational */}<br><br>            &lt;Activity mode={currentStep === &quot;educational&quot; ? &quot;visible&quot; : &quot;hidden&quot;}&gt;<br><br>              &lt;h2 className=&quot;text-md font-medium&quot;&gt;Educational Detail&lt;/h2&gt;<br>              &lt;Controller<br>                name=&quot;degree&quot;<br>                control={form.control}<br>                render={({ field, fieldState }) =&gt; (<br>                  &lt;Field&gt;<br>                    &lt;FieldLabel htmlFor=&quot;degree&quot;&gt;<br>                      Degree<br>                    &lt;/FieldLabel&gt;<br>                    &lt;Input<br>                      {...field}<br>                      placeholder=&quot;e.g. Bachelor in Accounting&quot;<br>                    /&gt;<br>                    {fieldState.invalid &amp;&amp; (&lt;FieldError errors={[fieldState.error]} /&gt;)}<br>                  &lt;/Field&gt;<br>                )}<br>              /&gt;<br><br>              &lt;Controller<br>                name=&quot;institute&quot;<br>                control={form.control}<br>                render={({ field, fieldState }) =&gt; (<br>                  &lt;Field&gt;<br>                    &lt;FieldLabel htmlFor=&quot;institute&quot;&gt;<br>                      Institute<br>                    &lt;/FieldLabel&gt;<br>                    &lt;Input<br>                      {...field}<br>                      placeholder=&quot;e.g. Oxford University&quot;<br>                    /&gt;<br>                    {fieldState.invalid &amp;&amp; (&lt;FieldError errors={[fieldState.error]} /&gt;)}<br>                  &lt;/Field&gt;<br>                )}<br>              /&gt;<br><br>              &lt;Controller<br>                name=&quot;startDate&quot;<br>                control={form.control}<br>                render={({ field, fieldState }) =&gt; (<br>                  &lt;Field&gt;<br>                    &lt;FieldLabel htmlFor=&quot;startDate&quot;&gt;<br>                      Start Date<br>                    &lt;/FieldLabel&gt;<br>                    &lt;Input<br>                      type=&quot;date&quot;<br>                      value={field.value ? (field.value as Date).toISOString().slice(0, 10) : &quot;&quot;}<br>                      onChange={(e) =&gt; field.onChange(e.target.value ? new Date(e.target.value) : null)}<br>                    /&gt;<br>                    {fieldState.invalid &amp;&amp; (&lt;FieldError errors={[fieldState.error]} /&gt;)}<br>                  &lt;/Field&gt;<br>                )}<br>              /&gt;<br><br>              &lt;Controller<br>                name=&quot;endDate&quot;<br>                control={form.control}<br>                render={({ field, fieldState }) =&gt; (<br>                  &lt;Field&gt;<br>                    &lt;FieldLabel htmlFor=&quot;endDate&quot;&gt;<br>                      End Date<br>                    &lt;/FieldLabel&gt;<br>                    &lt;Input<br>                      type=&quot;date&quot;<br>                      value={field.value ? (field.value as Date).toISOString().slice(0, 10) : &quot;&quot;}<br>                      onChange={(e) =&gt; field.onChange(e.target.value ? new Date(e.target.value) : null)}<br>                    /&gt;<br>                    {fieldState.invalid &amp;&amp; (&lt;FieldError errors={[fieldState.error]} /&gt;)}<br>                  &lt;/Field&gt;<br>                )}<br>              /&gt;<br><br>            &lt;/Activity&gt;<br>          &lt;/FieldGroup&gt;<br><br>        &lt;/form&gt;<br>      &lt;/CardContent&gt;<br><br>      &lt;CardFooter&gt;<br>        &lt;Field orientation={&quot;horizontal&quot;}&gt;<br><br>          {activeStep &gt; 0 &amp;&amp; (<br>            &lt;Button type=&quot;button&quot; variant=&quot;outline&quot; onClick={() =&gt; setActiveStep(i =&gt; i - 1)}&gt;<br>              Back<br>            &lt;/Button&gt;<br>          )}<br><br>          {activeStep &lt; steps.length - 1 &amp;&amp; (<br>            &lt;Button<br>              type=&quot;button&quot;<br>              onClick={async () =&gt; {<br>                const valid = form.trigger()<br>                setActiveStep(i =&gt; i + 1);<br>              }}<br>            &gt;<br>              Next<br>            &lt;/Button&gt;<br>          )}<br><br>          {<br>            activeStep === steps.length - 1 &amp;&amp;<br>            &lt;Button type=&quot;submit&quot; form=&quot;resume-form&quot;&gt;<br>              Submit<br>            &lt;/Button&gt;<br>          }<br>        &lt;/Field&gt;<br><br>        &lt;Toaster /&gt;<br>      &lt;/CardFooter&gt;<br>    &lt;/Card&gt;<br>  )<br>}</pre><p>Final Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*8HUsJZ3bMqi8NYGBXyIFEA.png" /><figcaption>Multi-step form</figcaption></figure><p>Please checkout the live preview and github link to understand the code more clearly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1138200fb9e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy Real-time chat application with Laravel and React]]></title>
            <link>https://medium.com/@iamsuman066/easy-real-time-chat-application-with-laravel-and-react-02b8934080d6?source=rss-480fb83e08cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/02b8934080d6</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[inertia-js]]></category>
            <category><![CDATA[polling]]></category>
            <dc:creator><![CDATA[Suman Shrestha]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 10:41:04 GMT</pubDate>
            <atom:updated>2025-04-29T10:41:50.693Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey, today we are going to build a simple, easy and fast way to create the realtime chat application with Laravel and ReactJs. First of all, lets begin with the starter pack as always to save our time on authentication and ui kit. You can always use this easy to follow documentation of laravel <a href="https://laravel.com/docs/12.x/starter-kits#react"><strong><em>here</em></strong></a><strong><em>. </em></strong>To achieve this realtime application we are going to use the polling method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GsfPPB4jg-0ctyTP" /><figcaption>Photo by <a href="https://unsplash.com/@vimarethomas?utm_source=medium&amp;utm_medium=referral">Thomas Vimare</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>So let’s begin.</p><blockquote>I assume that you have your project ready. So, let’s continue from there.</blockquote><blockquote>You can access this code <a href="https://github.com/heySuman/chat-pooling"><strong>here</strong></a>.</blockquote><ol><li>Start your server</li></ol><pre>composer install // to install all the packages in composer.json<br>npm install // to install the frontend packages from package.json<br>composer run dev // to start the server</pre><p>2. Create the migration for the message</p><pre>php artisan make:migration create_messages_table</pre><p>This create a new migration file in <em>database/migrations/ </em>that looks like<em> XXXX_create_messages_table.php. </em>Open it and update the code as following code snippet.</p><pre>&lt;?php<br><br>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br><br>return new class extends Migration<br>{<br>    /**<br>     * Run the migrations.<br>     */<br>    public function up(): void<br>    {<br>        Schema::create(&#39;messages&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;foreignId(&#39;sender&#39;)-&gt;constrained(&#39;users&#39;);<br>            $table-&gt;foreignId(&#39;receiver&#39;)-&gt;constrained(&#39;users&#39;);<br>            $table-&gt;text(&#39;message&#39;);<br>            $table-&gt;timestamps();<br>        });<br>    }<br><br>    /**<br>     * Reverse the migrations.<br>     */<br>    public function down(): void<br>    {<br>        Schema::dropIfExists(&#39;messages&#39;);<br>    }<br>};</pre><p>Now to create the table in the database, we have to migrate the above migration file. So, in the terminal paste the following command.</p><pre>php artisan migrate</pre><p>3. Create the model for the Message table</p><pre>php artisan make:model Message</pre><p>This command create the model file <em>Message.php</em> in the <em>app/Models </em>directory<em>. </em>Update the code to match the following code snnipet<em>.</em></p><pre>&lt;?php<br><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Model;<br>use Illuminate\Database\Eloquent\Relations\BelongsTo;<br><br>class Message extends Model<br>{<br>    protected $fillable = [<br>        &#39;sender&#39;,<br>        &#39;receiver&#39;,<br>        &#39;message&#39;,<br>    ];<br><br>    // relation to the user table<br>    public function sender(): BelongsTo<br>    {<br>        return $this-&gt;belongsTo(User::class, &#39;sender&#39;);<br>    }<br>    <br>    public function receiver(): BelongsTo<br>    {<br>        return $this-&gt;belongsTo(User::class, &#39;sender&#39;);<br>    }<br>}</pre><p>Open the <em>User.php</em> file in the same directory and add the relationship to the message table.</p><pre>&lt;?php<br><br>namespace App\Models;<br><br>// use Illuminate\Contracts\Auth\MustVerifyEmail;<br>use Illuminate\Database\Eloquent\Factories\HasFactory;<br>use Illuminate\Database\Eloquent\Relations\BelongsTo;<br>use Illuminate\Database\Eloquent\Relations\HasMany;<br>use Illuminate\Foundation\Auth\User as Authenticatable;<br>use Illuminate\Notifications\Notifiable;<br><br>class User extends Authenticatable<br>{<br>    /** @use HasFactory&lt;\Database\Factories\UserFactory&gt; */<br>    use HasFactory, Notifiable;<br><br>    /**<br>     * The attributes that are mass assignable.<br>     *<br>     * @var list&lt;string&gt;<br>     */<br>    protected $fillable = [<br>        &#39;name&#39;,<br>        &#39;email&#39;,<br>        &#39;password&#39;,<br>    ];<br><br>    /**<br>     * The attributes that should be hidden for serialization.<br>     *<br>     * @var list&lt;string&gt;<br>     */<br>    protected $hidden = [<br>        &#39;password&#39;,<br>        &#39;remember_token&#39;,<br>    ];<br><br>    /**<br>     * Get the attributes that should be cast.<br>     *<br>     * @return array&lt;string, string&gt;<br>     */<br>    protected function casts(): array<br>    {<br>        return [<br>            &#39;email_verified_at&#39; =&gt; &#39;datetime&#39;,<br>            &#39;password&#39; =&gt; &#39;hashed&#39;,<br>        ];<br>    }<br><br>    public function messages(): HasMany<br>    {<br>        return $this-&gt;hasMany(Message::class);<br>    }<br>}</pre><p>4. Create the controller to add for messaging.</p><pre>php artisan make:controller MessageController</pre><p>This command will create a file in <em>app/Http/Controllers</em> directory. Open the file and update it as well.</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use App\Models\Message;<br>use App\Models\User;<br>use Illuminate\Http\Request;<br><br>class MessageController extends Controller<br>{<br>    public function message(Request $request)<br>    {<br>        $validated = $request-&gt;validate([<br>            &#39;message&#39; =&gt; &#39;required|string&#39;,<br>            &#39;sender&#39; =&gt; &#39;required&#39;,<br>            &#39;receiver&#39; =&gt; &#39;required&#39;,<br>        ]);<br><br>        $message = Message::create($validated);<br><br>        return back()-&gt;with([&#39;message&#39; =&gt; $message]);<br>    }<br><br>    public function getMessages(Request $request, User $user)<br>    {<br>        $authId = auth()-&gt;id();<br>        $messages = Message::where(function ($query) use ($authId, $user) {<br>            $query-&gt;where(&#39;sender&#39;, $authId)<br>                -&gt;where(&#39;receiver&#39;, $user-&gt;id);<br>        })-&gt;orWhere(function ($query) use ($authId, $user) {<br>            $query-&gt;where(&#39;sender&#39;, $user-&gt;id)<br>                -&gt;where(&#39;receiver&#39;, $authId);<br>        })-&gt;orderBy(&#39;created_at&#39;, &#39;asc&#39;)-&gt;get();<br><br>        return response()-&gt;json($messages);<br>    }<br>}</pre><p>5. Create the route for the messages</p><p>Open up <em>routes/</em> directory and <em>web.php</em> and add the following routes.</p><pre><br>Route::get(&#39;messages/{user}&#39;, [MessageController::class, &#39;getMessages&#39;])-&gt;name(&#39;messages.get&#39;);<br>Route::post(&#39;messages&#39;, [MessageController::class, &#39;message&#39;])-&gt;name(&#39;messages.post&#39;);<br></pre><p>6. Create the route for the ui of the chat system</p><pre>Route::get(&#39;/chat&#39;, function () {<br>    return Inertia::render(&#39;Chat/Index&#39;, [<br>        &#39;users&#39; =&gt; User::where(&#39;id&#39;, &#39;!=&#39;, auth()-&gt;id())-&gt;get(),<br>    ]);<br>});</pre><p>7. Create UI for chat</p><p>Open <em>resources/js/pages </em>and create the <em>Chat </em>directory and add the <em>Index.php</em> file.</p><blockquote>Please make sure that file path should be: <em>resources/js/pages/Chat/Index.php</em></blockquote><p>Add the following code to create the ui for the chat.</p><pre>import { Button } from &#39;@/components/ui/button&#39;;<br>import { Input } from &#39;@/components/ui/input&#39;;<br>import { ScrollArea } from &#39;@/components/ui/scroll-area&#39;;<br>import Layout from &#39;@/layouts/app-layout&#39;;<br>import { SharedData, User } from &#39;@/types&#39;;<br>import { Head, usePage } from &#39;@inertiajs/react&#39;;<br>import axios from &#39;axios&#39;;<br>import { Mic, Send } from &#39;lucide-react&#39;;<br>import { useCallback, useEffect, useRef, useState } from &#39;react&#39;;<br><br>type Message = {<br>    id: number;<br>    receiver: number;<br>    sender: number;<br>    message: string;<br>    created_at: string | Date;<br>    updated_at: string | Date;<br>};<br>export default function Index({ users }: { users: User[] }) {<br>    const [messages, setMessages] = useState&lt;Message[]&gt;();<br>    const [selectedUser, setSelectedUser] = useState&lt;User | null&gt;(null);<br>    const [inputValue, setInputValue] = useState(&#39;&#39;);<br>    const messagesEndRef = useRef&lt;HTMLDivElement&gt;(null);<br>    const auth = usePage&lt;SharedData&gt;().props.auth;<br><br>    const scrollToBottom = useCallback(() =&gt; {<br>        messagesEndRef.current?.scrollIntoView({ behavior: &#39;smooth&#39; });<br>    }, []);<br><br>    useEffect(() =&gt; {<br>        scrollToBottom();<br>    }, [messages, scrollToBottom]);<br><br>    const [isSending, setIsSending] = useState(false);<br><br>    const handleSendMessage = async (userId: number) =&gt; {<br>        if (!inputValue.trim()) return;<br><br>        setIsSending(true);<br><br>        try {<br>            const payload = {<br>                id: 1000000,<br>                sender: auth.user.id,<br>                receiver: userId,<br>                message: inputValue,<br>                created_at: new Date(),<br>                updated_at: new Date(),<br>            };<br><br>            setMessages((prev) =&gt; [...(prev || []), payload]);<br>            setInputValue(&#39;&#39;);<br><br>            await axios.post(`/messages`, payload);<br>        } catch (error) {<br>            console.error(error);<br>        } finally {<br>            setIsSending(false);<br>        }<br>    };<br><br>    useEffect(() =&gt; {<br>        const handleFetchMessage = async () =&gt; {<br>            if (!selectedUser) return;<br><br>            const res = await axios.get(&#39;/messages/&#39; + selectedUser?.id);<br><br>            if (res.status === 200) {<br>                setMessages(res.data);<br>            }<br>        };<br><br>        handleFetchMessage();<br><br>        const timeInterval = 2000;<br>        const interval = setInterval(() =&gt; handleFetchMessage(), timeInterval);<br><br>        return () =&gt; clearInterval(interval);<br>    }, [selectedUser]);<br><br>    return (<br>        &lt;Layout&gt;<br>            &lt;Head title=&quot;Chat&quot; /&gt;<br>            &lt;div className=&quot;flex h-[90vh] w-full overflow-hidden border rounded&quot;&gt;<br>                {/* Sidebar - Users */}<br>                &lt;div className=&quot;w-1/4 border-r p-4 space-y-4 &quot;&gt;<br>                    &lt;h2 className=&quot;text-xl font-semibold&quot;&gt;Users&lt;/h2&gt;<br>                    {users.map((user) =&gt; (<br>                        &lt;Button<br>                            key={user.id}<br>                            variant={selectedUser?.id === user.id ? &#39;default&#39; : &#39;ghost&#39;}<br>                            className=&quot;w-full justify-start&quot;<br>                            onClick={() =&gt; setSelectedUser(user)}<br>                        &gt;<br>                            {user.name}<br>                        &lt;/Button&gt;<br>                    ))}<br>                &lt;/div&gt;<br><br>                {/* Chat area */}<br>                &lt;div className=&quot;flex flex-col w-3/4&quot;&gt;<br>                    {selectedUser ? (<br>                        &lt;&gt;<br>                            {/* Header */}<br>                            &lt;div className=&quot;border-b p-4 bg-background shadow-sm&quot;&gt;<br>                                &lt;h2 className=&quot;text-lg font-semibold&quot;&gt;{selectedUser.name}&lt;/h2&gt;<br>                            &lt;/div&gt;<br><br>                            {/* Messages area */}<br>                            &lt;ScrollArea className=&quot;flex-1 overflow-y-auto p-4&quot;&gt;<br>                                &lt;div className=&quot;space-y-2&quot;&gt;<br>                                    {messages?.map((message) =&gt; (<br>                                        &lt;div<br>                                            key={message.id}<br>                                            className={`flex ${message.sender === auth.user.id ? &#39;justify-end&#39; : &#39;justify-start&#39;}`}<br>                                        &gt;<br>                                            &lt;div<br>                                                className={`max-w-[75%] px-4 py-2 rounded-2xl text-sm ${<br>                                                    message.sender === auth.user.id<br>                                                        ? &#39;bg-primary text-primary-foreground rounded-br-none&#39;<br>                                                        : &#39;bg-muted rounded-bl-none&#39;<br>                                                }`}<br>                                            &gt;<br>                                                {message.message}<br>                                            &lt;/div&gt;<br>                                        &lt;/div&gt;<br>                                    ))}<br>                                    &lt;div ref={messagesEndRef} /&gt;<br>                                &lt;/div&gt;<br>                            &lt;/ScrollArea&gt;<br><br>                            {/* Input area */}<br>                            &lt;div className=&quot;border-t p-4&quot;&gt;<br>                                &lt;div className=&quot;flex items-center gap-2&quot;&gt;<br>                                    &lt;Input<br>                                        value={inputValue}<br>                                        onChange={(e) =&gt; setInputValue(e.target.value)}<br>                                        placeholder=&quot;Type a message...&quot;<br>                                        className=&quot;rounded-full px-4 py-2&quot;<br>                                        onKeyDown={(e) =&gt; {<br>                                            if (e.key === &#39;Enter&#39; &amp;&amp; inputValue.trim()) {<br>                                                handleSendMessage(selectedUser.id);<br>                                            }<br>                                        }}<br>                                    /&gt;<br>                                    &lt;Button<br>                                        onClick={() =&gt; handleSendMessage(selectedUser.id)}<br>                                        disabled={isSending || inputValue.trim() === &#39;&#39;}<br>                                        size=&quot;icon&quot;<br>                                        className=&quot;rounded-full&quot;<br>                                    &gt;<br>                                        &lt;Send className=&quot;h-5 w-5&quot; /&gt;<br>                                    &lt;/Button&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        &lt;/&gt;<br>                    ) : (<br>                        &lt;div className=&quot;flex-1 flex items-center justify-center text-muted-foreground&quot;&gt;<br>                            &lt;p&gt;Select a user to start chatting.&lt;/p&gt;<br>                        &lt;/div&gt;<br>                    )}<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/Layout&gt;<br><br>    );<br>}</pre><p>We have to install the necessary packages for this to run, we used shadcn ui for the components as well. Thus, install the following packages.</p><pre>npm i axios<br>npx shadcn@latest add input button scroll-area</pre><p>8. Register the new users.</p><p>Make sure you have run your server, with composer run dev command and you may access the site at <a href="http://127.0.0.1:8000/chat"><em>http://127.0.0.1:8000/</em></a></p><p>Register the new users. Once you have added at least two users, access this url <a href="http://127.0.0.1:8000/chat"><em>http://127.0.0.1:8000/chat</em></a></p><p>You should see something like this.</p><figure><img alt="Chat UI" src="https://cdn-images-1.medium.com/max/1024/1*el5N-GdfMuT630uRIzglew.png" /><figcaption>Chat UI</figcaption></figure><p>Now, you may chat with the other users in realtime.</p><p>Few things to note here,</p><ol><li>This method is not efficient, it rerenders the ui very often.</li><li>This method is not secure, the chat messages are not encypted or hashed.</li><li>This method shows how we can achieve realtime chat without using sockets.</li></ol><blockquote>Declaimer: Take this project as a fun project.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02b8934080d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Realtime chat application in Laravel 12 and React with Inertia Js]]></title>
            <link>https://medium.com/@iamsuman066/realtime-chat-application-in-laravel-12-and-react-with-inertia-js-7b7777e289b3?source=rss-480fb83e08cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b7777e289b3</guid>
            <category><![CDATA[chat-application]]></category>
            <category><![CDATA[inertia-js]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[pusher]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Suman Shrestha]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 05:55:35 GMT</pubDate>
            <atom:updated>2025-04-23T05:55:35.195Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xX8jJn1Q3U3u8bor" /><figcaption>Photo by <a href="https://unsplash.com/@danielleone?utm_source=medium&amp;utm_medium=referral">Daniel Leone</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello, today we are going to build a simple one to one chat application using the laravel 12 and inertia js with react. Before we begin, I hope you understand basic concepts in laravel and react js.</p><p>We are going to use Pusher as our broascasting driver and <strong>Laravel Echo,</strong> a JavaScript library that makes it painless to subscribe to channels and listen for events broadcast by your server-side broadcasting driver.</p><blockquote>GitHub Link: <a href="https://github.com/heySuman/chat-laravel">https://github.com/heySuman/chat-laravel</a></blockquote><p>Let’s begin.</p><blockquote>Note: If you want to integrate the chat feature, you may begin with step 2.</blockquote><h4>1. Make a project in Laravel 12 using the react starter kit.</h4><p>You can begin by following steps below.</p><pre>laravel new</pre><blockquote>Note: You must have composer installed in your computer.</blockquote><p>What is the name of your project?:</p><ul><li>realtime-chat or any of your choice</li></ul><p>Which starter kit would you like to install? [None]:</p><ul><li>React</li></ul><p>Which authentication provider do you prefer? [Laravel’s built-in]:</p><ul><li>laravel</li></ul><p>Which testing framework do you prefer? [Pest]:</p><ul><li>Pest or PHPUnit</li></ul><figure><img alt="Steps to create a project in laravel with react" src="https://cdn-images-1.medium.com/max/1024/1*R4knpssVDJXrgvf9-MKVBA.png" /><figcaption>Create a project in laravel 12 with starter kit react</figcaption></figure><p>After the successful installation, you can select any database of your choice, here we are going to use the SQLite.</p><p>Open the project of your choice, and open up the terminal and enter the following command.</p><pre>php artisan migrate // to create the tables in the database</pre><p>To install the dependencies.</p><pre>npm install</pre><p>To start server.</p><pre>composer run dev</pre><p>If all steps have been completed successfully, you can open link to access the starter kit at <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*juAwfGmsAaVC44Y5lCqczQ.png" /><figcaption>Starter Kit Landing page.</figcaption></figure><h4>2. Set up Pusher</h4><p>Go to the pusher.com and register.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6e_BUElw6oDK5C-97VTsA.png" /><figcaption>Register page for Pusher.com</figcaption></figure><p>After the succesful registration, you will be directed to the dashboard.</p><figure><img alt="Pusher.com dashboard" src="https://cdn-images-1.medium.com/max/1024/1*7G2RwhXnawuaI51JOyw2cw.png" /><figcaption>Pusher.com dashboard.</figcaption></figure><p>We will be using the Channels for our chat application, so lets start with the Channels. Start by clicking <strong>get started</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWildqFgk1s-vW_3EAkQaQ.png" /><figcaption>Select the pusher channel configuration</figcaption></figure><p>Select React in Frontend and Laravel in backend.</p><figure><img alt="Pusher channel project dashboard" src="https://cdn-images-1.medium.com/max/1024/1*VTtt27mA4CrArp42_Y0Eaw.png" /><figcaption>Project Dashboard</figcaption></figure><p>Go to the App Keys, copy the keys.</p><figure><img alt="Copying the app keys" src="https://cdn-images-1.medium.com/max/1024/1*ZGDc26eH2IF6IhNcsvmMkA.png" /><figcaption>App Keys</figcaption></figure><p>Go to the project and paste them in the .env file as following below code snippet.</p><pre>BROADCAST_DRIVER=pusher<br><br>PUSHER_APP_ID=YOUR_APP_ID<br>PUSHER_APP_KEY=YOUR_KEY<br>PUSHER_APP_SECRET=YOUR_SECRET_KEY<br>PUSHER_APP_CLUSTER=YOUR_APP_CLUSTER<br>PUSHER_PORT=443<br>PUSHER_SCHEME=https<br><br>VITE_PUSHER_APP_KEY=YOUR_APP_KEY<br>VITE_PUSHER_APP_CLUSTER=YOUR_APP_CLUSTER</pre><blockquote>Note: make sure you copy paste the keys properly in the above format.</blockquote><h4>3. Set up migration and controllers</h4><p>Let’s start the main part of our application, setting up the broadcasting and chat feature.</p><p>Create the Message table in the database.</p><pre>php artisan make:migration create_messages_table  </pre><p>Go to the folder database/migrations and open the migration file, it must be name something like <strong>2025_04_23_025316_create_messages_table.php</strong>.</p><p>Add the columns name <em>sender_id, receiver_id</em> and <em>message </em>to the table <strong>messages</strong>.</p><pre>&lt;?php<br><br>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br><br>return new class extends Migration<br>{<br>    /**<br>     * Run the migrations.<br>     */<br>    public function up(): void<br>    {<br>        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;)-&gt;onDelete(&#39;cascade&#39;);<br>            $table-&gt;foreignId(&#39;receiver_id&#39;)-&gt;constrained(&#39;users&#39;)-&gt;onDelete(&#39;cascade&#39;);<br>            $table-&gt;text(&#39;message&#39;);<br>            $table-&gt;timestamps();<br>        });<br>    }<br><br>    /**<br>     * Reverse the migrations.<br>     */<br>    public function down(): void<br>    {<br>        Schema::dropIfExists(&#39;messages&#39;);<br>    }<br>};</pre><p>Migrate this table to the database.</p><pre>php artisan migrate</pre><p>Create model for this table.</p><pre>php artisan make:model Message</pre><p>Open the folder app/Models/ and file Message.php.</p><pre>&lt;?php<br><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Model;<br>use Illuminate\Database\Eloquent\Relations\BelongsTo;<br><br>class Message extends Model<br>{<br>    protected $fillable = [<br>        &#39;sender_id&#39;,<br>        &#39;receiver_id&#39;,<br>        &#39;message&#39;,<br>    ];<br><br>    public function sender(): BelongsTo<br>    {<br>        return $this-&gt;belongsTo(User::class, &#39;sender_id&#39;);<br>    }<br><br>    public function receiver(): BelongsTo<br>    {<br>        return $this-&gt;belongsTo(User::class, &#39;receiver_id&#39;);<br>    }<br>}</pre><p>Add the relation to the User model as well, open the file User.php from folder app/Models.</p><pre>&lt;?php<br><br>namespace App\Models;<br><br>// use Illuminate\Contracts\Auth\MustVerifyEmail;<br>use Database\Factories\UserFactory;<br>use Illuminate\Database\Eloquent\Factories\HasFactory;<br>use Illuminate\Database\Eloquent\Relations\HasMany;<br>use Illuminate\Foundation\Auth\User as Authenticatable;<br>use Illuminate\Notifications\Notifiable;<br><br>class User extends Authenticatable<br>{<br>    /** @use HasFactory&lt;UserFactory&gt; */<br>    use HasFactory, Notifiable;<br><br>    /**<br>     * The attributes that are mass assignable.<br>     *<br>     * @var list&lt;string&gt;<br>     */<br>    protected $fillable = [<br>        &#39;name&#39;,<br>        &#39;email&#39;,<br>        &#39;password&#39;,<br>    ];<br><br>    /**<br>     * The attributes that should be hidden for serialization.<br>     *<br>     * @var list&lt;string&gt;<br>     */<br>    protected $hidden = [<br>        &#39;password&#39;,<br>        &#39;remember_token&#39;,<br>    ];<br><br>    /**<br>     * Get the attributes that should be cast.<br>     *<br>     * @return array&lt;string, string&gt;<br>     */<br>    protected function casts(): array<br>    {<br>        return [<br>            &#39;email_verified_at&#39; =&gt; &#39;datetime&#39;,<br>            &#39;password&#39; =&gt; &#39;hashed&#39;,<br>        ];<br>    }<br><br>    public function messages(): hasMany<br>    {<br>        return $this-&gt;hasMany(Message::class);<br>    }<br>}</pre><p>Create the controller for the Message.</p><pre>php artisan make:controller MessageController</pre><p>This command will create controller at app/Http/Controllers/.</p><p>Open up the MessageController.php and update the code.</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use App\Models\Message;<br>use Illuminate\Http\Request;<br><br>class MessageController extends Controller<br>{<br>    public function index(Request $request)<br>    {<br>        $receiverId = $request-&gt;query(&#39;receiver_id&#39;);<br><br>        $messages = Message::where(function ($q) use ($receiverId) {<br>            $q-&gt;where(&#39;sender_id&#39;, auth()-&gt;id())<br>                -&gt;where(&#39;receiver_id&#39;, $receiverId);<br>        })-&gt;orWhere(function ($q) use ($receiverId) {<br>            $q-&gt;where(&#39;sender_id&#39;, $receiverId)<br>                -&gt;where(&#39;receiver_id&#39;, auth()-&gt;id());<br>        })-&gt;orderBy(&#39;created_at&#39;)-&gt;get();<br><br>        return response()-&gt;json($messages);<br>    }<br><br>    public function store(Request $request)<br>    {<br>        $validated = $request-&gt;validate([<br>            &#39;receiver_id&#39; =&gt; &#39;required|exists:users,id&#39;,<br>            &#39;message&#39; =&gt; &#39;required|string|max:1000&#39;,<br>        ]);<br><br>        $message = Message::create([<br>            &#39;sender_id&#39; =&gt; auth()-&gt;id(),<br>            &#39;receiver_id&#39; =&gt; $validated[&#39;receiver_id&#39;],<br>            &#39;message&#39; =&gt; $validated[&#39;message&#39;],<br>        ]);<br><br>        return response()-&gt;json($message);<br>    }<br>}</pre><h4>4. Set up broadcasting</h4><p>Now lets create the broadcating.</p><pre>php artisan install:broadcasting</pre><p>This command will create the channels.php in the routes/ folder and add configuration file at config/ as broadcating.php</p><blockquote>Note: You may learn more at <a href="https://laravel.com/docs/11.x/broadcasting">https://laravel.com/docs/11.x/broadcasting</a></blockquote><p>Since, we are are working with the Pusher channel, we have to install the pusher driver.</p><pre>composer require pusher/pusher-php-server</pre><p>After the installation, we have to make the event for the message sent, so that we could listen to it, first lets create the broadcasting provider.</p><pre>php artisan make:provider BroadcastServiceProvider </pre><p>This command will create the service container for the broadcast at app/Providers as BroadcastServiceProvider.php</p><p>Open up the BroadcastServiceProvider.php and update the code</p><pre>&lt;?php<br><br>namespace App\Providers;<br><br>use Illuminate\Support\Facades\Broadcast;<br>use Illuminate\Support\ServiceProvider;<br><br>class BroadcastServiceProvider extends ServiceProvider<br>{<br>    /**<br>     * Register services.<br>     */<br>    public function register(): void<br>    {<br>        //<br>    }<br><br>    /**<br>     * Bootstrap services.<br>     */<br>    public function boot(): void<br>    {<br>        Broadcast::routes();<br><br>        require base_path(&#39;routes/channels.php&#39;);<br>    }<br>}</pre><p>Now let’s create the event for the message sent.</p><pre>php artisan make:event MessageSent</pre><p>This will create MessageSent.php at app/Events. Open and update the code.</p><pre>&lt;?php<br><br>namespace App\Events;<br><br>use App\Models\Message;<br>use Illuminate\Broadcasting\PrivateChannel;<br>use Illuminate\Contracts\Broadcasting\ShouldBroadcast;<br>use Illuminate\Queue\SerializesModels;<br><br>class MessageSent implements ShouldBroadcast<br>{<br>    use SerializesModels;<br><br>    public function __construct(public Message $message)<br>    {<br>    }<br><br>    public function broadcastOn(): PrivateChannel<br>    {<br>        return new PrivateChannel(&#39;chat.&#39; . $this-&gt;message-&gt;receiver_id);<br>    }<br><br>    public function broadcastWith(): array<br>    {<br>        return [<br>            &#39;id&#39; =&gt; $this-&gt;message-&gt;id,<br>            &#39;message&#39; =&gt; $this-&gt;message-&gt;message,<br>            &#39;sender_id&#39; =&gt; $this-&gt;message-&gt;sender_id,<br>            &#39;receiver_id&#39; =&gt; $this-&gt;message-&gt;receiver_id,<br>            &#39;created_at&#39; =&gt; $this-&gt;message-&gt;created_at-&gt;toDateTimeString(),<br>        ];<br>    }<br>}</pre><p>So here, we are creating the broadcast private channel with name <strong>chat </strong>and it should be made accessible to the reciever only.</p><p>Now, whenever we send the message we should broadcast it, thus, we need to update the <strong>MessageController.php</strong> to have it broadcast it the event.</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use App\Models\Message;<br>use App\Events\MessageSent;<br>use Illuminate\Http\Request;<br><br>class MessageController extends Controller<br>{<br>    public function index(Request $request)<br>    {<br>        $receiverId = $request-&gt;query(&#39;receiver_id&#39;);<br><br>        $messages = Message::where(function ($q) use ($receiverId) {<br>            $q-&gt;where(&#39;sender_id&#39;, auth()-&gt;id())<br>                -&gt;where(&#39;receiver_id&#39;, $receiverId);<br>        })-&gt;orWhere(function ($q) use ($receiverId) {<br>            $q-&gt;where(&#39;sender_id&#39;, $receiverId)<br>                -&gt;where(&#39;receiver_id&#39;, auth()-&gt;id());<br>        })-&gt;orderBy(&#39;created_at&#39;)-&gt;get();<br><br>        return response()-&gt;json($messages);<br>    }<br><br>    public function store(Request $request)<br>    {<br>        $validated = $request-&gt;validate([<br>            &#39;receiver_id&#39; =&gt; &#39;required|exists:users,id&#39;,<br>            &#39;message&#39; =&gt; &#39;required|string|max:1000&#39;,<br>        ]);<br><br>        $message = Message::create([<br>            &#39;sender_id&#39; =&gt; auth()-&gt;id(),<br>            &#39;receiver_id&#39; =&gt; $validated[&#39;receiver_id&#39;],<br>            &#39;message&#39; =&gt; $validated[&#39;message&#39;],<br>        ]);<br><br>        broadcast(new MessageSent($message))-&gt;toOthers();<br><br>        return response()-&gt;json($message);<br>    }<br>}</pre><h4><strong>5. Create Routes</strong></h4><p>Now, add the controller to the routes and configure the channels.php we created earlier.</p><p>Open up the web.php at routes/web.php and add the following code snippet.</p><pre>&lt;?php<br><br>use App\Models\User;<br>use Illuminate\Support\Facades\Route;<br>use Inertia\Inertia;<br>use App\Http\Controllers\MessageController;<br><br>Route::get(&#39;/&#39;, function () {<br>    return Inertia::render(&#39;welcome&#39;);<br>})-&gt;name(&#39;home&#39;);<br><br>Route::middleware([&#39;auth&#39;, &#39;verified&#39;])-&gt;group(function () {<br>    Route::get(&#39;dashboard&#39;, function () {<br>        return Inertia::render(&#39;dashboard&#39;);<br>    })-&gt;name(&#39;dashboard&#39;);<br>});<br><br>Route::middleware(&#39;auth&#39;)-&gt;group(function () {<br>    Route::get(&#39;/messages&#39;, [MessageController::class, &#39;index&#39;]);<br>    Route::post(&#39;/messages&#39;, [MessageController::class, &#39;store&#39;]);<br>});<br><br>Route::middleware(&#39;auth&#39;)-&gt;group(function () {<br>    Route::get(&#39;/chat/{user}&#39;, function (App\Models\User $user) {<br>        return Inertia::render(&#39;Chat/Show&#39;, [<br>            &#39;receiverId&#39; =&gt; $user-&gt;id,<br>            &#39;users&#39; =&gt; User::where(&#39;id&#39;, &#39;!=&#39;, auth()-&gt;id())-&gt;get(),<br>        ]);<br>    })-&gt;name(&#39;chat.show&#39;);<br><br>    Route::get(&#39;/chat&#39;, function (App\Models\User $user) {<br>        return Inertia::render(&#39;Chat/Index&#39;, [<br>            &#39;users&#39; =&gt; User::where(&#39;id&#39;, &#39;!=&#39;, auth()-&gt;id())-&gt;get(),<br>        ]);<br>    })-&gt;name(&#39;chat.index&#39;);<br>});<br><br>Broadcast::routes([&#39;middleware&#39; =&gt; [&#39;auth&#39;, &#39;web&#39;]]);;<br><br>require __DIR__ . &#39;/settings.php&#39;;<br>require __DIR__ . &#39;/auth.php&#39;;</pre><p>Open up the channels.php and update the code.</p><pre>&lt;?php<br><br>use Illuminate\Support\Facades\Broadcast;<br><br>/*<br>|--------------------------------------------------------------------------<br>| Broadcast Channels<br>|--------------------------------------------------------------------------<br>|<br>| Here you may register all of the event broadcasting channels that your<br>| application supports. The given channel authorization callbacks are<br>| used to check if an authenticated user can listen to the channel.<br>|<br>*/<br><br>// Private chat channel - Only the receiver can listen to this channel<br>Broadcast::channel(&#39;chat.{receiverId}&#39;, function ($user, $receiverId) {<br>    return (int) $user-&gt;id === (int) $receiverId;<br>});</pre><h4>6. Adding Frontend</h4><p>Let’s add the dependencies to the pusher and echo</p><pre>npm install --save laravel-echo pusher-js</pre><p>Now, create the bootstrap.ts at <strong>resources/js</strong> and add the following code.</p><pre>import Echo from &#39;laravel-echo&#39;;<br>import Pusher from &#39;pusher-js&#39;;<br>import axios from &#39;axios&#39;;<br><br>window.Pusher = Pusher;<br><br>window.Echo = new Echo({<br>    broadcaster: &#39;pusher&#39;,<br>    key: import.meta.env.VITE_PUSHER_APP_KEY,<br>    cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,<br>    forceTLS: true,<br>    encrypted: true,<br>    auth: {<br>        headers: {<br>            &#39;X-CSRF-TOKEN&#39;: document.querySelector(&#39;meta[name=&quot;csrf-token&quot;]&#39;).getAttribute(&#39;content&#39;)<br>        }<br>    }<br>});</pre><p>Open the app.blade.php from the <strong>resources/views</strong> and add the following code.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;{{ str_replace(&#39;_&#39;, &#39;-&#39;, app()-&gt;getLocale()) }}&quot; @class([&#39;dark&#39; =&gt; ($appearance ?? &#39;system&#39;) == &#39;dark&#39;])&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>    &lt;meta name=&quot;csrf-token&quot; content=&quot;{{ csrf_token() }}&quot;&gt;<br><br>    {{-- Inline script to detect system dark mode preference and apply it immediately --}}<br>    &lt;script&gt;<br>        (function() {<br>            const appearance = &#39;{{ $appearance ?? &quot;system&quot; }}&#39;;<br><br>            if (appearance === &#39;system&#39;) {<br>                const prefersDark = window.matchMedia(&#39;(prefers-color-scheme: dark)&#39;).matches;<br><br>                if (prefersDark) {<br>                    document.documentElement.classList.add(&#39;dark&#39;);<br>                }<br>            }<br>        })();<br>    &lt;/script&gt;<br><br>    {{-- Inline style to set the HTML background color based on our theme in app.css --}}<br>    &lt;style&gt;<br>        html {<br>            background-color: oklch(1 0 0);<br>        }<br><br>        html.dark {<br>            background-color: oklch(0.145 0 0);<br>        }<br>    &lt;/style&gt;<br><br>    &lt;title inertia&gt;{{ config(&#39;app.name&#39;, &#39;Laravel&#39;) }}&lt;/title&gt;<br><br>    &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.bunny.net&quot;&gt;<br>    &lt;link href=&quot;https://fonts.bunny.net/css?family=instrument-sans:400,500,600&quot; rel=&quot;stylesheet&quot; /&gt;<br><br>    @routes<br>    @viteReactRefresh<br>    @vite([&#39;resources/js/app.tsx&#39;, &quot;resources/js/pages/{$page[&#39;component&#39;]}.tsx&quot;])<br>    @inertiaHead<br>&lt;/head&gt;<br>&lt;body class=&quot;font-sans antialiased&quot;&gt;<br>@inertia<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now, let’s create the component for the chat interface, for this we will be using the shadcn-ui.</p><p>Create Chat folder in the <strong>resources/js/pages</strong> and add <strong>Index.tsx</strong> to it.</p><pre>import AppLayout from &#39;@/layouts/app-layout&#39;;<br>import { User } from &#39;@/types&#39;;<br>import { Head, Link } from &#39;@inertiajs/react&#39;;<br><br>export default function Index({ users }: { users: User[] }) {<br>    return (<br>        &lt;AppLayout&gt;<br>            &lt;Head title=&quot;Chat&quot; /&gt;<br>            &lt;div className={&#39;flex&#39;}&gt;<br>                &lt;div className={&#39;m-2 rounded w-full&#39;}&gt;<br>                    {users.map((user) =&gt; (<br>                        &lt;div key={user.id} className={&#39;p-2 border-b&#39;}&gt;<br>                            &lt;Link href={`/chat/${user.id}`}&gt;<br>                                &lt;p className={&#39;text-xl font-bold&#39;}&gt;{user.name}&lt;/p&gt;<br>                                &lt;p className={&#39;text-muted-foreground&#39;}&gt;Chat with {user.name}&lt;/p&gt;<br>                            &lt;/Link&gt;<br>                        &lt;/div&gt;<br>                    ))}<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/AppLayout&gt;<br>    );<br>}<br></pre><p>Add the Show.tsx in the same folder.</p><pre>import AppLayout from &#39;@/layouts/app-layout&#39;;<br>import { User } from &#39;@/types&#39;;<br>import { Head, Link } from &#39;@inertiajs/react&#39;;<br>import axios from &#39;axios&#39;;<br>import { useEffect, useState } from &#39;react&#39;;<br><br>type Message = {<br>    id: number;<br>    sender_id: number;<br>    receiver_id: number;<br>    message: string;<br>    created_at: string;<br>};<br><br>type Props = {<br>    auth: { user: { id: number; name: string } };<br>    receiverId: number;<br>    users: User[];<br>};<br><br>export default function Show({ auth, receiverId, users }: Props) {<br>    const [messages, setMessages] = useState&lt;Message[]&gt;([]);<br>    const [text, setText] = useState(&#39;&#39;);<br><br>    useEffect(() =&gt; {<br>        axios.get(`/messages?receiver_id=${receiverId}`).then((res) =&gt; {<br>            setMessages(res.data);<br>        });<br><br>        window.Echo.private(`chat.${auth.user.id}`).listen(&#39;MessageSent&#39;, (e: any) =&gt; {<br>            if (e.sender_id === receiverId) {<br>                setMessages((prev) =&gt; [...prev, e]);<br>            }<br>        });<br><br>        return () =&gt; {<br>            window.Echo.leave(`chat.${auth.user.id}`);<br>        };<br>    }, [auth.user.id, receiverId]);<br><br>    const sendMessage = () =&gt; {<br>        axios<br>            .post(&#39;/messages&#39;, {<br>                receiver_id: receiverId,<br>                message: text,<br>            })<br>            .then((res) =&gt; {<br>                setMessages((prev) =&gt; [...prev, res.data]);<br>                setText(&#39;&#39;);<br>            });<br>    };<br><br>    return (<br>        &lt;AppLayout&gt;<br>            &lt;Head title={`${users.find((user) =&gt; user.id === receiverId)?.name} `}/&gt;<br>            &lt;div className=&quot;flex&quot;&gt;<br>                &lt;div className=&quot;bg-muted m-2 w-1/3 overflow-y-auto rounded&quot;&gt;<br>                    {users.map((user) =&gt; (<br>                        &lt;div key={user.id} className={`m-2 cursor-pointer rounded p-4 ${user.id === receiverId ? &#39;bg-blue-100&#39; : &#39;bg-white&#39;}`}&gt;<br>                            &lt;Link href={route(&#39;chat.show&#39;, user.id)} className={&#39;text-xl font-bold&#39;}&gt;<br>                                &lt;p&gt;{user.name}&lt;/p&gt;<br>                            &lt;/Link&gt;<br>                        &lt;/div&gt;<br>                    ))}<br>                &lt;/div&gt;<br>                &lt;div className=&quot;p-4&quot;&gt;<br>                    &lt;div className=&quot;mb-2 h-96 overflow-y-auto border p-2&quot;&gt;<br>                        {messages.map((msg, i) =&gt; (<br>                            &lt;div key={i} className={msg.sender_id === auth.user.id ? &#39;text-right&#39; : &#39;text-left&#39;}&gt;<br>                                &lt;p className=&quot;inline-block rounded bg-gray-200 p-2&quot;&gt;{msg.message}&lt;/p&gt;<br>                            &lt;/div&gt;<br>                        ))}<br>                    &lt;/div&gt;<br>                    &lt;div className=&quot;flex gap-2&quot;&gt;<br>                        &lt;input type=&quot;text&quot; className=&quot;w-full border p-2&quot; value={text} onChange={(e) =&gt; setText(e.target.value)} /&gt;<br>                        &lt;button className=&quot;bg-blue-500 px-4 text-white&quot; onClick={sendMessage}&gt;<br>                            Send<br>                        &lt;/button&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/AppLayout&gt;<br>    );<br>}</pre><p>To add the chat in the frontend, you have to add the chat in the navbar items which is present in <strong>resources/js/components/app-sidebar.tsx</strong>.</p><pre>import { NavFooter } from &#39;@/components/nav-footer&#39;;<br>import { NavMain } from &#39;@/components/nav-main&#39;;<br>import { NavUser } from &#39;@/components/nav-user&#39;;<br>import { Sidebar, SidebarContent, SidebarFooter, SidebarHeader, SidebarMenu, SidebarMenuButton, SidebarMenuItem } from &#39;@/components/ui/sidebar&#39;;<br>import { type NavItem } from &#39;@/types&#39;;<br>import { Link } from &#39;@inertiajs/react&#39;;<br>import { BookOpen, Folder, LayoutGrid, MessageCircleCodeIcon } from &#39;lucide-react&#39;;<br>import AppLogo from &#39;./app-logo&#39;;<br><br>const mainNavItems: NavItem[] = [<br>    {<br>        title: &#39;Dashboard&#39;,<br>        href: &#39;/dashboard&#39;,<br>        icon: LayoutGrid,<br>    },<br>    {<br>        title: &#39;Chat&#39;,<br>        href: &#39;/chat&#39;,<br>        icon: MessageCircleCodeIcon,<br>    },<br>];<br><br>const footerNavItems: NavItem[] = [<br>    {<br>        title: &#39;Repository&#39;,<br>        href: &#39;https://github.com/laravel/react-starter-kit&#39;,<br>        icon: Folder,<br>    },<br>    {<br>        title: &#39;Documentation&#39;,<br>        href: &#39;https://laravel.com/docs/starter-kits&#39;,<br>        icon: BookOpen,<br>    },<br>];<br><br>export function AppSidebar() {<br>    return (<br>        &lt;Sidebar collapsible=&quot;icon&quot; variant=&quot;inset&quot;&gt;<br>            &lt;SidebarHeader&gt;<br>                &lt;SidebarMenu&gt;<br>                    &lt;SidebarMenuItem&gt;<br>                        &lt;SidebarMenuButton size=&quot;lg&quot; asChild&gt;<br>                            &lt;Link href=&quot;/dashboard&quot; prefetch&gt;<br>                                &lt;AppLogo /&gt;<br>                            &lt;/Link&gt;<br>                        &lt;/SidebarMenuButton&gt;<br>                    &lt;/SidebarMenuItem&gt;<br>                &lt;/SidebarMenu&gt;<br>            &lt;/SidebarHeader&gt;<br><br>            &lt;SidebarContent&gt;<br>                &lt;NavMain items={mainNavItems} /&gt;<br>            &lt;/SidebarContent&gt;<br><br>            &lt;SidebarFooter&gt;<br>                &lt;NavFooter items={footerNavItems} className=&quot;mt-auto&quot; /&gt;<br>                &lt;NavUser /&gt;<br>            &lt;/SidebarFooter&gt;<br>        &lt;/Sidebar&gt;<br>    );<br>}</pre><p>Now the app is ready, lets create the new users and test our app.</p><figure><img alt="Creating users" src="https://cdn-images-1.medium.com/max/1024/1*jwdfKEENjpBLDRLuf9qIuA.png" /><figcaption>Account Creation</figcaption></figure><p>To test we will use different profile to see if the realtime update happens or not.</p><figure><img alt="Testing application" src="https://cdn-images-1.medium.com/max/1024/1*rx9AtrD--JrC7IVySFqU1Q.png" /><figcaption>Testing</figcaption></figure><figure><img alt="testing application" src="https://cdn-images-1.medium.com/max/1024/1*7Ktqkh772CMunEMT99pmtg.png" /><figcaption>Testing.</figcaption></figure><p>If any issues arises, please let me know. Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b7777e289b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>