<?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 Sinan Bekar on Medium]]></title>
        <description><![CDATA[Stories by Sinan Bekar on Medium]]></description>
        <link>https://medium.com/@sinan.bekar?source=rss-f657e69ed04------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*i2fpjjxXRwCdrDwV2BrHgg.jpeg</url>
            <title>Stories by Sinan Bekar on Medium</title>
            <link>https://medium.com/@sinan.bekar?source=rss-f657e69ed04------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 08:09:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sinan.bekar/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[React Modal Component Implementation]]></title>
            <link>https://medium.com/@sinan.bekar/react-modal-component-implementation-ee599ef229fa?source=rss-f657e69ed04------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee599ef229fa</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[modal]]></category>
            <dc:creator><![CDATA[Sinan Bekar]]></dc:creator>
            <pubDate>Fri, 14 Jan 2022 13:04:06 GMT</pubDate>
            <atom:updated>2022-01-14T13:04:06.375Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to build a simple yet powerful modal component. <strong>(CRA, Next.js and TypeScript)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4g6GsBUFbctoqNjnzXK7fg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@lautaroandreani?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lautaro Andreani</a> on <a href="https://unsplash.com/s/photos/reactjs?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Modals (also called a modal window, modal popup, modal dialog) display content that temporarily blocks interactions with the main view of the UI. In this tutorial, we will build a simple yet powerful modal component for our React project.</p><p>At the end of the tutorial, there will be a live demo.</p><p>Let’s get started.</p><p>First, we need to create React Portal.</p><blockquote>React Portal is a first-class way to render child components into a DOM node outside of the parent DOM hierarchy defined by the component tree hierarchy. The Portal’s most common use cases are when the child components need to visually break out of the parent container like modal boxes, tooltips, hovercards, loaders…</blockquote><h4>Creating React Portal in CRA</h4><p>Edit public/index.html and add:</p><pre>   &lt;body&gt;<br>      &lt;noscript&gt;You need to enable JavaScript to run this app.&lt;/noscript&gt;<br>      &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>      &lt;--- Add this ---&gt;<br>      &lt;div id=&quot;modal-root&quot;&gt;&lt;/div&gt;<br>   &lt;/body&gt;</pre><h4>Creating React Portal in Next.js</h4><p>Create _document.jsx or _document.tsx if you are using TypeScript.</p><pre>import Document, { Html, Head, Main, NextScript } from &#39;next/document&#39;</pre><pre>class MyDocument extends Document {<br>  static async getInitialProps(context) {<br>    const initialProps = await Document.getInitialProps(context)<br>    return { ...initialProps }<br>  }</pre><pre>  render() {<br>    return (<br>      &lt;Html&gt;<br>        &lt;Head /&gt;<br>        &lt;body&gt;<br>          &lt;Main /&gt;<br>          &lt;NextScript /&gt;<br>        &lt;/body&gt;<br>      &lt;/Html&gt;<br>    )<br>  }<br>}</pre><pre>export default MyDocument</pre><p>For TypeScript, import DocumentContext and type context in getInitialProps so like this: getInitialProps(context: DocumentContext)</p><p>Add before &lt;/body&gt; :</p><p>&lt;div id=”modal-root”&gt;&lt;/div&gt;</p><h4>Creating useOnClickOutside hook</h4><p>We will create useOnClickOutsidehook which accepts React.SetStateActionas a parameter, we will pass the setShowModal state action. This hook will help us to manage outside clicks, for the inside close click, there will be another handle method.</p><p>The hook will create a ref inside and process it for click handling then return this ref.</p><p>We will attach this ref to the modal and it will check if clicked outside or inside the modal.</p><p>There will be another option for re-render or hide &amp; show by CSS display property on close and open. This option is very useful for some scenarios.</p><h4>JS:</h4><p>Completed hooks/useOnClickOutside.jsfile:</p><pre>import React from &quot;react&quot;;</pre><pre>const useOnClickOutside = (handle) =&gt; {<br>  const ref = React.useRef(null);<br>  const handleClickOutside = (e) =&gt; {<br>    if (ref.current &amp;&amp; !ref.current.contains(e.target)) {<br>      handle(e);<br>    }<br>  };<br>  React.useEffect(() =&gt; {<br>    window.addEventListener(&quot;click&quot;, handleClickOutside, true);<br>    return () =&gt; {<br>      window.removeEventListener(&quot;click&quot;, handleClickOutside, true);<br>    };<br>  });<br>  return ref;<br>};<br>export default useOnClickOutside;</pre><h4>TypeScript:</h4><p>Completed hooks/useOnClickOutside.tsfile:</p><pre>import React from &quot;react&quot;;</pre><pre>const useOnClickOutside = (<br>  handle: (<br>    e:<br>      | MouseEvent<br>      | React.MouseEvent&lt;HTMLElement&gt;<br>  ) =&gt; void) =&gt; {<br>  <br>  const ref = React.useRef&lt;HTMLInputElement&gt;(null);</pre><pre>const handleClickOutside = (e: MouseEvent) =&gt; {<br>    if (ref.current &amp;&amp; !ref.current.contains(e.target as Node)) {<br>      handle(e);<br>    }<br>  };</pre><pre>React.useEffect(() =&gt; {<br>    window.addEventListener(&quot;click&quot;, handleClickOutside, true);<br>    return () =&gt; {<br>      window.removeEventListener(&quot;click&quot;, handleClickOutside, true);<br>    };<br>  });</pre><pre>return ref;<br>};</pre><pre>export default useOnClickOutside;</pre><h4>Modal Component</h4><p>Create components/modal.js or tsx. Create modal.css.</p><p>Import React, ReactDom, useOnClickOutside hook and modal.css to modal.js</p><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;<br>import useOnClickOutside from &quot;../hooks/useOnClickOutside&quot;;<br>import &quot;../modal.css&quot;;</pre><p>Create modal const, showModal will be our state and setShowModal will be our setStateAction. title and reRenderOnCloseOpen are will be optional.</p><pre>const Modal = ({<br>  showModal,<br>  setShowModal,<br>  children,<br>  title = &quot;&quot;,<br>  reRenderOnCloseOpen = true<br>}) =&gt; {};</pre><p>handleCloseClick will be used both on the close button and the close outside hook.</p><pre>const handleCloseClick = (e) =&gt; {<br>  e.preventDefault();<br>  setShowModal(false);<br>};</pre><pre>const ref = useOnClickOutside(handleCloseClick);</pre><p>We will attach the ref object to modal-main instead of modal-container.</p><pre>const modalContent = (showModal || !reRenderOnCloseOpen) &amp;&amp; (<br>    &lt;div<br>      className={`modal-container ${<br>        !showModal &amp;&amp; !reRenderOnCloseOpen ? &quot;hidden&quot; : &quot;&quot;<br>      }<br>    `}<br>    &gt;<br>      &lt;div ref={ref} className=&quot;modal-main&quot;&gt;<br>        &lt;div className=&quot;relative&quot;&gt;<br>          &lt;div className=&quot;absolute right-0&quot;&gt;<br>            &lt;button onClick={handleCloseClick}&gt;x&lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>          &lt;div&gt;{title}&lt;/div&gt;<br>          &lt;div&gt;{children}&lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );</pre><p>At the end of the code, we need to return with ReactPortal .</p><p><strong>For CRA:</strong></p><pre>return ReactDOM.createPortal(<br>    modalContent,<br>    document.getElementById(&quot;modal-root&quot;)<br>);</pre><p><strong>For Next.js: </strong>We need to check if the window is attached to the DOM because of the <strong>hydration</strong> progress.</p><pre>if (typeof window !== &quot;undefined&quot;) {<br>    return ReactDOM.createPortal(<br>      modalContent,<br>      document.getElementById(&quot;modal-root&quot;)<br>    );<br>  } else {<br>    return null;<br>  }</pre><h4>Completed Modal Component</h4><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;<br>import useOnClickOutside from &quot;../hooks/useOnClickOutside&quot;;<br>import &quot;../modal.css&quot;;</pre><pre>const Modal = ({<br>  showModal,<br>  setShowModal,<br>  children,<br>  title = &quot;&quot;,<br>  reRenderOnCloseOpen = true<br>}) =&gt; {<br>  const handleCloseClick = (e) =&gt; {<br>    e.preventDefault();<br>    setShowModal(false);<br>  };</pre><pre>const ref = useOnClickOutside(handleCloseClick);<br>  const modalContent = (showModal || !reRenderOnCloseOpen) &amp;&amp; (<br>    &lt;div<br>      className={`modal-container ${<br>        !showModal &amp;&amp; !reRenderOnCloseOpen ? &quot;hidden&quot; : &quot;&quot;<br>      }<br>    `}<br>    &gt;<br>      &lt;div ref={ref} className=&quot;modal-main&quot;&gt;<br>        &lt;div className=&quot;relative&quot;&gt;<br>          &lt;div className=&quot;absolute right-0&quot;&gt;<br>            &lt;button onClick={handleCloseClick}&gt;x&lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>          &lt;div&gt;{title}&lt;/div&gt;<br>          &lt;div&gt;{children}&lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );</pre><pre>return ReactDOM.createPortal(<br>    modalContent,<br>    document.getElementById(&quot;modal-root&quot;)<br>  );<br>};<br>export default Modal;</pre><p><strong>For the Typescript:</strong></p><p>Add<strong> Props</strong> interface:</p><pre>interface Props {<br>  showModal: boolean;<br>  setShowModal: React.Dispatch&lt;React.SetStateAction&lt;boolean&gt;&gt;;<br>  title?: string;<br>  reRenderOnCloseOpen?: boolean;<br>}</pre><p>Change const Modal = to const Modal: React.FC&lt;Props&gt; =</p><p>Add type to handleCloseClick’s e parameter (e: React.MouseEvent&lt;HTMLElement&gt; | MouseEvent)</p><p>Also do not forget to check hydration when returning the portal object for Next.js.</p><h4>Styling</h4><p>Edit the modal.css and add these:</p><pre>.modal-container {<br>  position: fixed;<br>  top: 0;<br>  width: 100%;<br>  height: 100%;<br>  z-index: 999;<br>  display: flex;<br>  justify-content: center;<br>  align-items: center;<br>}</pre><pre>.modal-main {<br>  width: 18rem;<br>  height: 20rem;<br>  border-radius: 0.5rem;<br>  padding: 1rem;<br>  background-color: #464646;<br>  color: white;<br>}</pre><pre>.flex {<br>  display: flex;<br>}</pre><pre>.hidden {<br>  display: none;<br>}<br>.right-0 {<br>  right: 0;<br>}</pre><pre>.relative {<br>  position: relative;<br>}</pre><pre>.absolute {<br>  position: absolute;<br>}</pre><p><strong>Usage:</strong></p><pre>import Modal from &quot;./components/Modal&quot;;<br>import React from &quot;react&quot;;</pre><pre>export default function App() {<br>  const [showModal, setShowModal] = React.useState(false);</pre><pre>return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;button<br>        onClick={() =&gt; {<br>          setShowModal(true);<br>        }}<br>      &gt;<br>        Open Modal<br>      &lt;/button&gt;<br>      &lt;Modal<br>        title=&quot;Example Modal&quot;<br>        showModal={showModal}<br>        setShowModal={setShowModal}<br>      &gt;<br>        &lt;div&gt;ModalContent&lt;/div&gt;<br>      &lt;/Modal&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Live Demo: </strong><a href="https://codesandbox.io/s/react-modal-8zsxk">https://codesandbox.io/s/react-modal-8zsxk</a></p><h3>Final Words</h3><p>In this tutorial, we implemented a simple yet powerful Modal. You can improve it as you want if you get the main idea.</p><p>You can check my GitHub if you want to see my other works.</p><p><a href="https://github.com/sinanbekar">https://github.com/sinanbekar</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee599ef229fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Real-Time Chat App with Laravel and React]]></title>
            <link>https://towardsdev.com/build-a-real-time-chat-app-with-laravel-and-react-5cae5a7c22d4?source=rss-f657e69ed04------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cae5a7c22d4</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[real-time-communication]]></category>
            <category><![CDATA[chat]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Sinan Bekar]]></dc:creator>
            <pubDate>Thu, 23 Dec 2021 13:42:15 GMT</pubDate>
            <atom:updated>2022-01-18T12:44:01.266Z</atom:updated>
            <content:encoded><![CDATA[<h4>Laravel Echo, Breeze, Socket.io, Redis, Inertia.js, TailwindCSS stack</h4><p><strong>Laravel</strong> and <strong>React</strong> are awesome, thanks to <strong>WebSocket protocol</strong> and easy-to-use <strong>Laravel Echo</strong> library, we can build real-time applications easily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yHDsAGZFFnOamXoPYXW4tQ.jpeg" /></figure><p>In this article, we will be using <strong>Laravel Echo Server </strong>as <strong>socket.io</strong> server which has <strong>Laravel Echo</strong> compatibility.</p><p><strong>Laravel Echo Server </strong>and <strong>Laravel 8 </strong>communication will be handled by<strong> Redis.</strong></p><p>We will kick start our application without building auth system with <strong>Laravel Breeze</strong> also with <strong>Inertia.js</strong> we don’t need to write API for <strong>React</strong> and <strong>Laravel</strong> communication. In addition to these, we will be using <strong>TailwindCSS</strong> for styling which also comes default with <strong>Breeze React </strong>stack.</p><p>You can find the completed demo repo and production demo link at the bottom.</p><h3>Getting Started with Laravel Setup</h3><p><strong>Step 1</strong> — Create a new Laravel project as guided in the <a href="https://laravel.com/docs/8.x/installation">official documentation</a>.</p><p><strong>Docker </strong>(<strong>Laravel Sail</strong>) is the best and fastest way to develop Laravel apps if you ask me. Simply change “example-app” to anything you like and run the following command in your terminal:</p><pre>curl -s https://laravel.build/example-app | bash</pre><p>then <strong>cd</strong> to folder and run:</p><pre>./vendor/bin/sail up -d</pre><p>First <strong>sail up</strong> command could take a long time.</p><p>You can access Laravel Welcome page with<strong> </strong><a href="http://localhost/"><strong>http://localhost</strong></a></p><p>Set sail as an alias:</p><pre>alias sail=&#39;[ -f sail ] &amp;&amp; bash sail || bash vendor/bin/sail&#39;</pre><p>With setting alias, you don’t need to type<strong> ./vendor/bin</strong>.</p><p>If you don’t have <strong>npm</strong>, <strong>yarn</strong> or <strong>node</strong> in your system, you can use sail npm, sail yarn, sail node.</p><p><strong>Step 2 </strong>— Installing <strong>Breeze</strong> package</p><blockquote><a href="https://github.com/laravel/breeze">Laravel Breeze</a> is a minimal, simple implementation of all of Laravel’s <a href="https://laravel.com/docs/8.x/authentication">authentication features</a>, including login, registration, password reset, email verification, and password confirmation. Laravel Breeze’s default view layer is made up of simple <a href="https://laravel.com/docs/8.x/blade">Blade templates</a> styled with <a href="https://tailwindcss.com/">Tailwind CSS</a>.</blockquote><p>Run:</p><p>sail composer require laravel/breeze --dev</p><p>Extracting package with React scaffold:</p><pre>sail artisan breeze:install react</pre><p>Now run the following for installing packages and migration:</p><pre>npm install &amp;&amp; npm run dev</pre><pre>sail artisan migrate</pre><p><strong>Step 3 </strong>— Docker configuration</p><p>Open <strong>docker-compose.yml</strong> and add bolded ones.</p><pre>.<br>.<br>.<br>        networks:<br>            - sail<br><strong>    laravel-echo-server:<br>        image: &#39;oanhnn/laravel-echo-server&#39;<br>        ports:<br>            - &#39;6001:6001&#39;<br>        volumes:<br>            - &#39;${PWD}/laravel-echo-server.json:/app/laravel-echo-server.json&#39;<br>        networks:<br>            - sail</strong></pre><pre>networks:<br>    sail:<br>        driver: bridge<br>.<br>.<br>.</pre><p>Create <strong>laravel-echo-server.json</strong> to root folder and paste this for the development environment. You<strong> should </strong>make changes later for production.</p><pre>{<br>    &quot;authHost&quot;: &quot;<a href="http://laravel.test/">http://laravel.test</a>&quot;,<br>    &quot;authEndpoint&quot;: &quot;/broadcasting/auth&quot;,<br>    &quot;clients&quot;: [],<br>    &quot;database&quot;: &quot;redis&quot;,<br>    &quot;databaseConfig&quot;: {<br>        &quot;redis&quot;: {<br>            &quot;port&quot;: &quot;6379&quot;,<br>            &quot;host&quot;: &quot;redis&quot;,<br>   &quot;keyPrefix&quot;: &quot;laravel_database_&quot;<br>        }<br>    },<br>    &quot;devMode&quot;: true,<br>    &quot;host&quot;: null,<br>    &quot;port&quot;: &quot;6001&quot;,<br>    &quot;protocol&quot;: &quot;http&quot;,<br>    &quot;socketio&quot;: {},<br>    &quot;sslCertPath&quot;: &quot;&quot;,<br>    &quot;sslKeyPath&quot;: &quot;&quot;,<br>    &quot;subscribers&quot;: {<br>        &quot;http&quot;: true,<br>        &quot;redis&quot;: true<br>    },<br>    &quot;apiOriginAllow&quot;: {<br>        &quot;allowCors&quot;: true,<br>        &quot;allowOrigin&quot;: &quot;<a href="http://localhost/">http://localhost</a>&quot;,<br>        &quot;allowMethods&quot;: &quot;GET, POST&quot;,<br>        &quot;allowHeaders&quot;: &quot;Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id&quot;<br>    }<br>}</pre><p>Delete the container and create a new one:</p><pre>sail down &amp;&amp; sail up -d</pre><p><strong>Step 4 </strong>— Laravel basic configurations</p><p>Uncomment <strong>App\Providers\BroadcastServiceProvider::class </strong>in <strong>config/app.php</strong></p><p>Set <strong>BROADCAST_DRIVER</strong> to <strong>redis</strong> in <strong>.env</strong> environment variables file.</p><p><strong>Step 5 </strong>— Install client packages</p><pre>npm install --save laravel-echo socket.io-client@2.4.0</pre><p>Add this code to<strong> </strong><strong>/resources/js/bootstrap.js</strong></p><pre>import Echo from &#39;laravel-echo&#39;;</pre><pre>window.io = require(&#39;socket.io-client&#39;);</pre><pre>window.Echo = new Echo({<br>    broadcaster: &#39;socket.io&#39;,<br>    host: window.location.hostname + &#39;:6001&#39;,<br>});</pre><h3>Testing Echo Server</h3><p>Create test event by using artisan:</p><pre>sail artisan make:event TestEvent</pre><p>We will create a public channel (no auth required) for testing manually and returning<strong> </strong><strong>[‘title’ =&gt; ‘Test Title’, ‘message’ =&gt; ‘Test Message’] </strong>array.</p><p><strong>TestEvent </strong>event should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2c5320fc0ed819905af7b9148807b42/href">https://medium.com/media/a2c5320fc0ed819905af7b9148807b42/href</a></iframe><p>Now add a testing route for broadcasting:</p><pre>Route::get(&#39;add-notification&#39;, function () {<br>    broadcast(new \App\Events\TestEvent);<br>    return &#39;Test&#39;;<br>});</pre><p>Add this to <strong>/resources/js/bootstrap.js </strong>(only for temporary, delete after testing)</p><pre>window.Echo.channel(&#39;test-channel&#39;).listen(&#39;TestEvent&#39;, event =&gt; {<br>    console.log(event);<br>});</pre><p>Compile the frontend assets (Mix):</p><pre>npm run dev</pre><p>Go to <strong>http://localhost</strong>, on another tab go to <strong>http://localhost/add-notification .</strong></p><p>You should see <strong>broadcastWith()</strong> return data in the welcome page console.</p><h3>Building the Chat App</h3><p><strong>Step 1 </strong>— Creating Models and Migrations</p><p>Create a <strong>Message model</strong> with artisan:</p><pre>sail artisan make:model Message --migration</pre><p>Go to <strong>database/migrations </strong>folder and add ‘<strong>user_id’</strong>, ‘<strong>room_id</strong>’ and ‘<strong>message</strong>’ columns to the <strong>messages table</strong> migration file:</p><pre>$table-&gt;integer(&#39;user_id&#39;)-&gt;unsigned();<br>$table-&gt;integer(&#39;room_id&#39;)-&gt;unsigned();<br>$table-&gt;text(&#39;message&#39;);</pre><p>Create a <strong>Room</strong> <strong>model</strong> with artisan:</p><pre>sail artisan make:model Room --migration</pre><p>In the same folder, add <strong>‘name’</strong> column to the <strong>rooms table</strong> migration file:</p><pre>$table-&gt;string(&#39;name&#39;)-&gt;unique();</pre><p>You can delete timestamps if you want.</p><p>Migrate changes. You can also clear the cache with sail artisan cache:clearif you get an error.</p><pre>sail artisan migrate</pre><p>Now we will establish relationships by adding methods to models.</p><p>In the<strong> Message model </strong>set ‘<strong>message</strong>’ and ‘<strong>room_id</strong>’ fillable, add <strong>user()</strong> and <strong>room() </strong>method.</p><pre>protected $fillable = [&#39;message&#39;, &#39;room_id&#39;];</pre><pre>public function user()<br>    {<br>        return $this-&gt;belongsTo(User::class);<br>    }<br>    <br>    public function room()<br>    {<br>        return $this-&gt;belongsTo(Room::class);<br>    }</pre><p>In the <strong>Room model </strong>set ‘<strong>name</strong>’ fillable and add <strong>messages()</strong> method.</p><pre>protected $fillable = [&#39;name&#39;];</pre><pre>public function messages()<br>    {<br>        return $this-&gt;hasMany(Message::class);<br>    }</pre><p>Add this method to the <strong>User</strong> <strong>model</strong>:</p><pre>public function messages()<br>    {<br>        return $this-&gt;hasMany(Message::class);<br>    }</pre><p><strong>Step 2 </strong>— MessageSent event</p><p>Create a <strong>MessageSent</strong> <strong>event</strong> with artisan:</p><pre>sail artisan make:event MessageSent</pre><p>Now we will be setting <strong>User</strong>, <strong>Room </strong>and <strong>Message</strong> object properties, returning Presence channel in <strong>broadcastOn()</strong> method for auth requirement also instead of passing all model objects data, we will be passing specific broadcasting data to the client for security reasons.</p><p><strong>MessageSent</strong> event should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5ad47239a838c40b2671a0ea5811ab8/href">https://medium.com/media/b5ad47239a838c40b2671a0ea5811ab8/href</a></iframe><p><strong>Step 3 </strong>— Generating some database data using tinker</p><p>Run tinker with the following:</p><pre>sail artisan tinker</pre><p>Run the following command to create five users:</p><pre>\App\Models\User::factory(5)-&gt;create();</pre><p>Run the following command to create rooms:</p><pre>DB::table(&#39;rooms&#39;)-&gt;insert(array_map(function ($room) {<br>            return [&#39;name&#39; =&gt; $room];<br>        }, [&#39;general&#39;, &#39;room1&#39;, &#39;room2&#39;, &#39;room3&#39;, &#39;room4&#39;]));<br>}</pre><p><strong>Step 4 </strong>— Creating controller and setting routing configurations</p><p>Create a <strong>ChatsController</strong> with artisan:</p><pre>sail artisan make:controller ChatsController</pre><p>In the controller with <strong>renderChat()</strong> method, we are rendering a chat page with saved messages, room data; with <strong>sendMessage()</strong> method we are creating new message data to the database.</p><p>Completed <strong>ChatsController</strong> should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0e8ba6e8614f03fe761001315a92171/href">https://medium.com/media/c0e8ba6e8614f03fe761001315a92171/href</a></iframe><p><strong>/broadcasting/auth </strong>is the auth request channel route.</p><p>We will allow only logged users (with presence channel) and all logged users can get auth.</p><p><strong>routes/channel.php</strong></p><pre>Broadcast::channel(&#39;room.{id}&#39;, function ($user) {<br>    return $user-&gt;only(&#39;id&#39;, &#39;name&#39;);<br>});</pre><p>Add routes for chat page and message POST request:</p><p><strong>routes/web.php</strong></p><pre>Route::middleware([&#39;auth&#39;, &#39;verified&#39;])-&gt;group(function () {<br>    Route::get(&#39;/chat/{room?}&#39;,  [ChatsController::class, &#39;renderChat&#39;])-&gt;name(&#39;chat&#39;);<br>    Route::post(&#39;/message&#39;, [ChatsController::class, &#39;sendMessage&#39;])-&gt;name(&#39;message&#39;);<br>});</pre><p><strong>Step 5 </strong>— Setting up the client-side</p><p>We will listen to events using <strong>Laravel Echo</strong> library’s methods.</p><p>We will join presence channel with<strong> </strong><strong>join()</strong>, getting active users with <strong>here()</strong>,<strong> </strong>handling <strong>‘user joining’</strong> event with <strong>joining()</strong>, handling <strong>‘user leaving’</strong> event with <strong>leaving()</strong>, real-time messages with <strong>listen()</strong>, handling <strong>‘typing event’</strong> with<strong> </strong><strong>listenForWhisper()</strong></p><p>We need to chain these methods in <strong>componentDidMount()</strong> lifecycle method.</p><p><strong>leave()</strong> method <strong>must</strong> be called in <strong>componentWillUnmount() </strong>lifecycle method for handling ‘<strong>leaving user’</strong> event.</p><p>Basically, we will fetch all messages that the room has before on the first render, message sending event will be handled real-time by socket then we will post it to the database.</p><p>Go to <strong>resources/js/Components</strong> and create <strong>Chat.js</strong>. Chat component should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d350449c1929f42d7699800596d06f9/href">https://medium.com/media/2d350449c1929f42d7699800596d06f9/href</a></iframe><p>Go to <strong>resources/js/Pages/</strong> and create <strong>Chat.js:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7642c3d2a9360379ac4d9b0196580383/href">https://medium.com/media/7642c3d2a9360379ac4d9b0196580383/href</a></iframe><p>Compile the frontend assets (Mix):</p><pre>npm run dev</pre><p>Now you can access the chat page by visiting <a href="http://localhost/chat"><strong>http://localhost/chat</strong></a></p><p><strong>Production demo: </strong>(Customized)</p><p><a href="http://laravel-chat-app.ml/"><strong>http://laravel-chat-app.ml/</strong></a></p><p>The completed project is on Github.</p><p><a href="https://github.com/sinanbekar/laravel-realtime-chat-app">GitHub - sinanbekar/laravel-realtime-chat-app: Laravel real time chat app demo. Step by step explained in Medium article.</a></p><h3>Final Words</h3><p>In this article, I discussed how you could easily setup a real-time chat app with Laravel and modern technologies.</p><p>Of course, this is the simplest implementation. You need to do better configuration and tweaks for large production and security.</p><p>If you need further help with the code or the application setup, do leave a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cae5a7c22d4" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/build-a-real-time-chat-app-with-laravel-and-react-5cae5a7c22d4">Build a Real-Time Chat App with Laravel and React</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>