<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Saurabh Mahajan</title>
    <description>The latest articles on DEV Community by Saurabh Mahajan (@100r0bh).</description>
    <link>https://dev.to/100r0bh</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F631016%2Ffbf5d828-f294-45a5-b4ad-bfa8bd015729.jpeg</url>
      <title>DEV Community: Saurabh Mahajan</title>
      <link>https://dev.to/100r0bh</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/100r0bh"/>
    <language>en</language>
    <item>
      <title>Using Service Container to create Objects in Laravel</title>
      <dc:creator>Saurabh Mahajan</dc:creator>
      <pubDate>Sat, 16 Apr 2022 09:25:57 +0000</pubDate>
      <link>https://dev.to/100r0bh/using-service-container-to-create-objects-in-laravel-24gf</link>
      <guid>https://dev.to/100r0bh/using-service-container-to-create-objects-in-laravel-24gf</guid>
      <description>&lt;p&gt;Recently I tweeted about using Service Container to create an Object instead of using the &lt;code&gt;new&lt;/code&gt; Keyword and it led to a lot of questions. &lt;br&gt;
&lt;iframe class="tweet-embed" id="tweet-1492044765314965504-860" src="https://platform.twitter.com/embed/Tweet.html?id=1492044765314965504"&gt;
&lt;/iframe&gt;

  // Detect dark theme
  var iframe = document.getElementById('tweet-1492044765314965504-860');
  if (document.body.className.includes('dark-theme')) {
    iframe.src = "https://platform.twitter.com/embed/Tweet.html?id=1492044765314965504&amp;amp;theme=dark"
  }



&lt;/p&gt;

&lt;p&gt;In this article, we will see how to create objects using  Service Container and some of its benefits.&lt;/p&gt;

&lt;p&gt;Let's say we have a &lt;code&gt;Transistor&lt;/code&gt; class as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\Services;

class Transistor {
    public function __construct()
    {
    }
    .
    .
    .
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, if we want to use this Class in the index method of our Controller, we would do something like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function index()
{
    $transistor = new Transistor();
    .
    .    
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, the way Laravel works under the hood, we can simply inject our Transistor Class like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function index(Transistor $transistor)
{
    //$transistor object will be available here.
    .
    .

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Laravel is automatically able to resolve the Transistor Class and able to inject it into our method (This is also known as Dependency Injection).&lt;/p&gt;

&lt;p&gt;In fact, you might have been using this Laravel Feature even without knowing it. Ever wondered how &lt;code&gt;Request&lt;/code&gt; Class gets injected into your Controller Methods.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function store(Request $request)
{
.
.    
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, currently our Transistor Class has, what we call, Zero Configuration so Laravel is able to resolve the Class on its own. Now let us say that our Transistor Class expected a parameter via Constructor as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\Services;

class Transistor {
    public $key;

    public function __construct($key)
    {
        $this-&amp;gt;key = $key;
    }
    .
    .
    .
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now since our Transistor Class expects a parameter, Laravel would not be able to resolve the Class on its own. We will need to tell Laravel how to resolve this Class. We can do so in &lt;code&gt;AppServiceProvider&lt;/code&gt; as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$this-&amp;gt;app-&amp;gt;bind(Transistor::class, function () {
    return new Transistor(config('settings.key'));
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So now every time, we ask for the Transistor Class to be injected, Laravel will look into the Service Provider and inject the Class as we have defined.&lt;/p&gt;

&lt;p&gt;Laravel Service Container supports many other type of Binding, which are beyond the scope of this Article. You can check them in the &lt;a href="https://laravel.com/docs/9.x/container#binding" rel="noopener noreferrer"&gt;Documentation&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Now, some of the benefits of using the Service Container to resolve your Classes are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Controller is no longer responsible for creating the Object. We just inject the Object into the Controller and Controller is only responsible for calling the methods related to Transistor Class. This removes a lot of noise and helps to keep our Controller Clean.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If the implementation of our Transistor class changes in the future, let's say our Transistor Class requires another parameter to be passed via constructor, we only need to make changes at one single location. Without Service Container, we will have to make changes at every file where Transistor Class is being used.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Using Service Container makes it very easy to Mock the Transistor Class using Tests.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$mock = $this-&amp;gt;mock(Transistor::class, function (MockInterface $mock) {
    $mock-&amp;gt;shouldReceive('fetchStations')-&amp;gt;once();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is even more useful when our Transistor Class is hitting a Third Party API and we want to avoid hitting the API during our Tests so as to avoid Rate Limit as well as make our Tests faster. &lt;/p&gt;

&lt;p&gt;Without using Service Container, it would not be easy to Mock our Transistor Class.&lt;/p&gt;

&lt;p&gt;In conclusion, if you are using &lt;code&gt;new&lt;/code&gt; to create an Object in Laravel, there is a probably a better way.&lt;/p&gt;

</description>
      <category>laravel</category>
    </item>
    <item>
      <title>Using Scope to improve Code readability.</title>
      <dc:creator>Saurabh Mahajan</dc:creator>
      <pubDate>Sat, 16 Apr 2022 08:01:41 +0000</pubDate>
      <link>https://dev.to/100r0bh/using-scope-to-improve-code-readiblity-1o14</link>
      <guid>https://dev.to/100r0bh/using-scope-to-improve-code-readiblity-1o14</guid>
      <description>&lt;p&gt;Laravel Query Scope is one of my favorite feature and its the one that I use extensively as it helps to keep code clean and make it more readable.&lt;/p&gt;

&lt;p&gt;Let's suppose we have the following Code in Controller which fetches all the Posts which are active.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Post::query()
    -&amp;gt;where('active', 1)
    -&amp;gt;get();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A very simple query with one where clause. Let's convert this where Clause to a Scope. We will go to Post Model and will create a method. We will call it &lt;code&gt;scopeActive&lt;/code&gt;. The method name must being with &lt;code&gt;scope&lt;/code&gt;. It will have Eloquent\Builder passed to it automatically. So we will define our method like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function scopeActive( $query ) 
{
    return $query-&amp;gt;where('active', 1);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can now use utilize this Scope and our Controller Code will become as below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Post::query()
    -&amp;gt;active()
    -&amp;gt;get();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can now use our &lt;code&gt;active&lt;/code&gt; scope anywhere in our code and Laravel will automatically convert it into query. Not a big improvement, you might say, but let's look at the following example where we need to get Active Posts which are created between 2 dates.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Post::query()
    -&amp;gt;where('active', 1)
    -&amp;gt;whereBetween('created_at', [
        $startDate . ' 00:00:00',
        $endDate .' 23:59:59'
    ])
    -&amp;gt;get();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's create a scope for this. We will call it &lt;code&gt;scopeBetween&lt;/code&gt; and it will accept 2 parameters, &lt;code&gt;$startDate&lt;/code&gt; and &lt;code&gt;$endDate&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function scopeBetween($query, $startDate, $endDate)
{
    $endDate .= ' 23:59:59';
    return $query-&amp;gt;whereBetween('created_at', [
        $startDate,
        $endDate
    ]);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And now we can change our Controller Code as below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Post::query()
    -&amp;gt;active()
    -&amp;gt;between($startDate, $endDate)
    -&amp;gt;get();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we compare this, our code is much more readable and a lot of noise has been removed. And we are starting to see the benefit of using Scopes.&lt;/p&gt;

&lt;p&gt;Let us have another scenario where we want to retrieve active  Posts created during Last Month. Our Code without Scope would look like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Post::query()
    -&amp;gt;where('active', 1)
    -&amp;gt;whereBetween('created_at', [
        Carbon::now()-&amp;gt;startOfMonth()-&amp;gt;subMonthNoOverflow(),
        Carbon::now()-&amp;gt;subMonthNoOverflow()-&amp;gt;endOfMonth()
    ])
    -&amp;gt;get();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let us define a Scope as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function scopeLastMonth($query)
{
    $startDate = Carbon::now()-&amp;gt;startOfMonth()-&amp;gt;subMonthNoOverflow();
    $endDate = Carbon::now()-&amp;gt;subMonthNoOverflow()-&amp;gt;endOfMonth();

    return $query-&amp;gt;whereBetween('created_at', [
        $startDate,
        $endDate
    ]);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And our Code which uses the above scope becomes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Post::query()
    -&amp;gt;active()
    -&amp;gt;lastMonth()
    -&amp;gt;get();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, we can encapsulate our complex or repeating conditions within the scope. We can give a meaningful name to our Scopes. And then use those scopes in our code which drastically improves the readability of our code.&lt;/p&gt;

</description>
      <category>laravel</category>
    </item>
    <item>
      <title>JS Timer using AlpineJs with Carbon Format</title>
      <dc:creator>Saurabh Mahajan</dc:creator>
      <pubDate>Wed, 09 Mar 2022 10:58:56 +0000</pubDate>
      <link>https://dev.to/100r0bh/js-timer-using-alpinejs-with-carbon-format-1c96</link>
      <guid>https://dev.to/100r0bh/js-timer-using-alpinejs-with-carbon-format-1c96</guid>
      <description>&lt;p&gt;If you have used Carbon Class in PHP, then you might have heard about the method &lt;code&gt;Carbon::diffForHumans()&lt;/code&gt;. It returns the difference between 2 dates in a Human Readable Form.&lt;/p&gt;

&lt;p&gt;So if difference is less than 60 seconds, the output would be in seconds. If the difference is more than 60 seconds, the output would be in minutes. If the difference is more than 60 minutes, the output would be in hours and so on.&lt;/p&gt;

&lt;p&gt;Recently I had to built a Timer in JS which should the elapsed Time in a similar manner. I choose to built the Timer using AlpineJS.&lt;/p&gt;

&lt;p&gt;I choose to call my Component &lt;code&gt;moment&lt;/code&gt; because I have been a big fan of &lt;code&gt;moment.js&lt;/code&gt;. The Component had a prop of &lt;code&gt;seconds&lt;/code&gt; which would hold the number of seconds that timer would need to display.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;span x-data="moment"&amp;gt;
&amp;lt;/span&amp;gt;

&amp;lt;script&amp;gt;
    function moment() {
        return {
            seconds: 1,
        }
    }
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next I created an &lt;code&gt;init&lt;/code&gt; method which would set the initial value of the timer.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;span x-data="moment" x-init="init(40)"&amp;gt;
&amp;lt;/span&amp;gt;

&amp;lt;script&amp;gt;
    function moment() {
        return {
            seconds: 1,
            init(seconds) {
                this.seconds = seconds;
            },
        }
    }
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, within this init method, I would use &lt;code&gt;setInterval&lt;/code&gt; to call a closure after each second. Within the closure, I would increment the value of &lt;code&gt;seconds&lt;/code&gt; prop. I would also create an &lt;code&gt;interval&lt;/code&gt; prop which I could use to close the Timer.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interval: "",
init(seconds) {
    this.seconds = seconds;
    this.interval = setInterval(() =&amp;gt; {
        this.seconds++;
    }, 1000);
},
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next I will create a method to display the Timer, I will call it &lt;code&gt;getTimeElapsed&lt;/code&gt; and use it as below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;span x-data="moment" x-init="init(40)"&amp;gt;
    &amp;lt;span x-text="getTimeElapsed"&amp;gt;&amp;lt;/span&amp;gt;
&amp;lt;/span&amp;gt;

.
.
.
            getTimeElapsed() {
                return this.seconds;
            }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At this stage the Timer would be working well and it will increment after each second. Now, we would format the &lt;code&gt;getTimeElapsed&lt;/code&gt; method so that it would return the data similar to Carbon method.&lt;/p&gt;

&lt;p&gt;In order to do so, I created an &lt;code&gt;intervals&lt;/code&gt; property like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    intervals: [
      { label: "hour", seconds: 3599 },
      { label: "minute", seconds: 59 },
      { label: "second", seconds: 1 }
    ],
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And then I used this property within the &lt;code&gt;getTimeElapsed&lt;/code&gt; as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getTimeElapsed() {
    const interval = this.intervals.find((i) =&amp;gt; i.seconds &amp;lt; this.seconds);
    const count = Math.floor(this.seconds / interval.seconds);
    return `${count} ${interval.label}${count !== 1 ? "s" : ""} ago`;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will display the difference in seconds and as soon as the difference crosses 59 seconds, it would display the difference in minutes and so on. I only needed difference till hours so I only defined &lt;code&gt;interval&lt;/code&gt; props till 3600. If you need to display days, you can define further.&lt;/p&gt;

&lt;p&gt;My last requirement was to Stop the Timer as soon as it crossed 2 hours. So I used the following check in &lt;code&gt;getTimeElapsed&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (this.seconds &amp;gt; 7200) {
    clearInterval(this.interval);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The beauty of AlpineJS is that you can define multiple of these Components on your page and each will behave independently of each other. You can check the implementation at the &lt;a href="https://codepen.io/100r0bh/pen/jOaQqmB"&gt;CodePen&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Hope you have enjoyed this tutorial. For similar articles, you can follow me on &lt;a href="https://twitter.com/TheLaravelDev"&gt;Twitter&lt;/a&gt;&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>alpinejs</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Limiting Pusher Connections with Laravel</title>
      <dc:creator>Saurabh Mahajan</dc:creator>
      <pubDate>Fri, 04 Mar 2022 06:14:27 +0000</pubDate>
      <link>https://dev.to/100r0bh/limiting-pusher-connections-with-laravel-190f</link>
      <guid>https://dev.to/100r0bh/limiting-pusher-connections-with-laravel-190f</guid>
      <description>&lt;p&gt;Laravel allows you to &lt;a href="https://laravel.com/docs/9.x/broadcasting#introduction"&gt;Broadcast&lt;/a&gt; Server Side Events over a WebSocket Connection. This allows you to update your Frontend when a certain action is initiated or completed on Server, without User having to refresh their screen, thereby improving the User experience.&lt;/p&gt;

&lt;p&gt;Laravel supports multiple drivers to implement Broadcasting, with &lt;a href="https://pusher.com/"&gt;Pusher&lt;/a&gt; being one of the famous drivers. It allows you to have 100 Concurrent Connections in the Free Plan. Depending upon your usage, you might need one of their &lt;a href="https://pusher.com/channels/pricing"&gt;Paid Plan&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;We had implemented the same on &lt;a href="https://laravelshift.com/"&gt;Laravel Shift&lt;/a&gt;, most noticeably on &lt;a href="https://laravelshift.com/can-i-upgrade-laravel"&gt;Can I Upgrade Laravel&lt;/a&gt;, which allows you to determine if your dependencies are compatible. All the other pages using Pusher were behind login and not publicly accessible.&lt;/p&gt;

&lt;p&gt;Just before Laravel 9 was due to be released, the number of visitors to the Shift increased and we had to upgrade to a higher Pusher Plan to keep up with the Concurrent Connections. As the release buzz passed, the number of visitors were going back to pre-release levels, however the number of Concurrent Connections hadn't fallen by as much.&lt;/p&gt;

&lt;p&gt;On further investigation we found out that a New Connection was being established for every visitor on the Site. Ideally a Connection should only be established when a User visits a Page which has functionality related to Pusher. However, a New Connection was getting established even if User Visited the Home Page. With the large number of Users that visit Laravel Shift, this was definitely a problem that we needed to address.&lt;/p&gt;

&lt;p&gt;Laravel Documentation recommends adding the following code to  &lt;code&gt;bootstrap.js&lt;/code&gt; inside &lt;code&gt;/resources/js&lt;/code&gt; in order to enable Pusher.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Echo from 'laravel-echo';

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    forceTLS: true
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We soon found out that whenever Pusher encounters the code &lt;code&gt;new Echo({...&lt;/code&gt;, it starts a New Connection. Since this code was present in &lt;code&gt;bootstrap.js&lt;/code&gt; which was being loaded on every page of the website (compiled via Laravel Mix), a connection was being established on every Page.&lt;/p&gt;

&lt;p&gt;So once we figured out the root cause, we just moved the above code from &lt;code&gt;bootstrap.js&lt;/code&gt; to a New JS File &lt;code&gt;custom.js&lt;/code&gt;. We then injected this JS File using &lt;a href="https://laravel.com/docs/9.x/blade#stacks"&gt;Stacks&lt;/a&gt; only on the pages where we were using Pusher.&lt;/p&gt;

&lt;p&gt;We immediately saw a big decrease in the number of Connections after this fix and the numbers have been steady since then. In the hindsight, it is something which should have been obvious and could easily have been avoided. Fortunately it wasn't a very costly mistake.&lt;/p&gt;

</description>
      <category>laravel</category>
    </item>
    <item>
      <title>Laravel Toast Component using Tailwind and Alpine</title>
      <dc:creator>Saurabh Mahajan</dc:creator>
      <pubDate>Mon, 24 Jan 2022 10:24:29 +0000</pubDate>
      <link>https://dev.to/100r0bh/laravel-toast-component-using-tailwind-and-alpine-48e4</link>
      <guid>https://dev.to/100r0bh/laravel-toast-component-using-tailwind-and-alpine-48e4</guid>
      <description>&lt;p&gt;In this Article, we will see how to create a Toast Component and make it customisable by allowing for different types and positions.&lt;/p&gt;

&lt;p&gt;First of all we are going to create a Component File in &lt;code&gt;resources/views/components/&lt;/code&gt; directory. We are going to call it &lt;code&gt;alert.blade.php&lt;/code&gt; and we can call it in Blade File using below syntax&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;x-alert&amp;gt;&amp;lt;/x-alert&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are going to pass the message that we want to display in between the 2 tags.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;x-alert&amp;gt;You are Logged in!&amp;lt;/x-alert&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This message will be available to the component as &lt;code&gt;$slot&lt;/code&gt; variable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div&amp;gt;
    {{$slot}}
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let us design it using some Tailwind CSS Classes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div&amp;gt;
    &amp;lt;div class="bg-blue-500 border-blue-700 max-w-xs text-white rounded-lg px-4 py-2"&amp;gt;
        {{$slot}}
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have applied following classes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;bg-blue-500: This gives a background color of Blue Shade.&lt;/li&gt;
&lt;li&gt;border-blue-700: This gives a border of slightly darker Blue Shade.&lt;/li&gt;
&lt;li&gt;max-w-xs: This limits the maximum widht that div can take.&lt;/li&gt;
&lt;li&gt;text-white: This gives the white color to the message&lt;/li&gt;
&lt;li&gt;rounded-lg: This gives the border radius to the div.&lt;/li&gt;
&lt;li&gt;px-4 py-2: They give a padding to the div.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;At this stage our alert component is displayed depending upon where it is rendered in the Blade File. However, we want to display it in a fixed position at bottom right of the screen. To do this, we will give Tailwind CSS Classes to the outer div.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div class="bottom-4 right-4 fixed"&amp;gt;
    &amp;lt;div class="bg-blue-500 border-blue-700 max-w-xs text-white rounded-lg px-4 py-2"&amp;gt;
        {{$slot}}
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;fixed&lt;/code&gt; class gives it a fixed Position and &lt;code&gt;bottom-4&lt;/code&gt; and &lt;code&gt;right-4&lt;/code&gt; place it at the bottom right of the screen. At this stage we can include our Component anywhere in our Blade File and it will display at the bottom right of the screen. &lt;/p&gt;

&lt;p&gt;Lets make our Component a bit more flexible. Currently it only display every message in Blue Shade. However, we want to support error, warning and success message type along with the info message type which will be default. We are going to add type as &lt;code&gt;@props&lt;/code&gt;. And we are going to change the CSS classes based on the type property.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@props(['type' =&amp;gt; 'info'])

@php
    $typeClasses = [
        'info' =&amp;gt; 'bg-blue-500 border-blue-700',
        'warning' =&amp;gt; 'bg-yellow-500 border-yellow-700',
        'error' =&amp;gt; 'bg-red-500 border-red-700',
        'success' =&amp;gt; 'bg-green-500 border-green-700',
    ][$type];
@endphp

&amp;lt;div class="bottom-4 right-4 fixed"&amp;gt;
    &amp;lt;div class="{{$typeClasses}} max-w-xs text-white rounded-lg px-4 py-2"&amp;gt;
        {{$slot}}
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we can call our Alert Component by passing type as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;x-alert type="error"&amp;gt;Record was not Saved.&amp;lt;/x-alert&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And the Component will be displayed with a shade of red color. If you do not pass any type, it will default to info.&lt;/p&gt;

&lt;p&gt;Similarly, we are going to allow our Component to take position as props. We will support 4 positions, bottom-right, bottom-left, top-right, top-left. Our Component will look like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@props(['type' =&amp;gt; 'info', 'position' =&amp;gt; 'bottom-right'])

@php
    $typeClasses = [
        'info' =&amp;gt; 'bg-blue-500 border-blue-700',
        'warning' =&amp;gt; 'bg-yellow-500 border-yellow-700',
        'error' =&amp;gt; 'bg-red-500 border-red-700',
        'success' =&amp;gt; 'bg-green-500 border-green-700',
    ][$type];

    $positionClasses = [
        'bottom-right' =&amp;gt; 'bottom-4 right-4',
        'bottom-left' =&amp;gt; 'bottom-4 left-4',
        'top-right' =&amp;gt; 'top-4 right-4',
        'top-left' =&amp;gt; 'top-4 left-4',
    ][$position]
@endphp

&amp;lt;div class="{{$positionClasses}} fixed"&amp;gt;
    &amp;lt;div class="{{$typeClasses}} max-w-xs text-white rounded-lg px-4 py-2"&amp;gt;
        {{$slot}}
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can try by calling the component as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;x-alert type="error" position="top-right"&amp;gt;
    Profile was saved successfully.
&amp;lt;/x-alert&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And we also want User to close this Notification when they click on it. we are going to use AlpineJs for it. We will create a &lt;code&gt;show&lt;/code&gt; property and use &lt;code&gt;x-show&lt;/code&gt; directive to change the display of our Component. Using the &lt;code&gt;@click&lt;/code&gt; directive we will change the value of &lt;code&gt;show&lt;/code&gt; to &lt;code&gt;false&lt;/code&gt;. We will also use the class cursor-pointer to change the Cursor to Pointer.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div class="{{$positionClasses}} fixed cursor-pointer"
    x-data="{show:true}"
    x-show="show"
    @click="show=false"
&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And with that our Component is complete and we can use this Component anywhere in our Laravel Project. If you are interested in more complex implementation using Livewire, please check out this &lt;a href="https://github.com/ascsoftw/livewire-toast"&gt;package&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;Hope you have enjoyed this tutorial. For similar articles, you can follow me on &lt;a href="https://twitter.com/TheLaravelDev"&gt;Twitter&lt;/a&gt;&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>tailwindcss</category>
      <category>alpinejs</category>
    </item>
    <item>
      <title>Livewire Button Component with Loading Indicator</title>
      <dc:creator>Saurabh Mahajan</dc:creator>
      <pubDate>Sat, 22 Jan 2022 09:39:09 +0000</pubDate>
      <link>https://dev.to/100r0bh/livewire-button-component-with-loading-indicator-5h77</link>
      <guid>https://dev.to/100r0bh/livewire-button-component-with-loading-indicator-5h77</guid>
      <description>&lt;p&gt;In this Article, we will see how to customize our Button to have following Animation using Livewire and extract everything into a Blade Component so as to reuse anywhere into your application.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/nyAmCKhog1tUpKmw8G/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/nyAmCKhog1tUpKmw8G/giphy.gif" alt="Preview" width="480" height="116"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We are going to use the Breeze Button Component and extend it according to our needs. Its definition looks like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button {{ $attributes-&amp;gt;merge(['type' =&amp;gt; 'submit']) }}&amp;gt;
    {{ $slot }}
&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I have removed all the CSS Classes for clarify.We can use this Button Component inside our Livewire Component like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;x-button wire:click="save" wire:loading.attr="disabled"&amp;gt;
    Save
&amp;lt;/x-button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What we want is that whenever this button is clicked, we want to change the Text to Saving. In order to do that we will use the &lt;code&gt;wire:loading&lt;/code&gt; property.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;x-button wire:click="save" wire:loading.attr="disabled"&amp;gt;
    Save
    &amp;lt;span wire:loading&amp;gt;Saving..&amp;lt;/span&amp;gt;
&amp;lt;/x-button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So now "Saving.." will get displayed as long as the submit button is clicked. And it will get hidden when the AJAX Call has finished. However, during this AJAX Call both "Save" and "Saving.." are showing. So we also need to hide the "Save" during this AJAX Call. We can do so using &lt;code&gt;wire:loading.remove&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;x-button wire:click="save" wire:loading.attr="disabled"&amp;gt;
    &amp;lt;span wire:loading.remove&amp;gt;Save&amp;lt;/span&amp;gt;
    &amp;lt;span wire:loading&amp;gt;Saving..&amp;lt;/span&amp;gt;
&amp;lt;/x-button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, even though this is working, this will lead to unexpected issues when you have more than 1 button on the Page. So it is always a good practice to specify that we only want to change the display of these elements when the AJAX Call corresponding to save method is being called. We can do so using &lt;code&gt;wire:target&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;x-button wire:click="save" wire:loading.attr="disabled"&amp;gt;
    &amp;lt;span wire:loading.remove wire.target="save"&amp;gt;Save&amp;lt;/span&amp;gt;
    &amp;lt;span wire:loading wire.target="save"&amp;gt;Saving..&amp;lt;/span&amp;gt;
&amp;lt;/x-button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At this stage, you should see your buttons having the same behaviour as shared at the start of the Article. However, we can further improve the readability of our code by extracting the code to our Button Component. We want this to be as simple as following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;x-button wire:click="save" loading="Saving.."&amp;gt;
  Save
&amp;lt;/x-button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First of all we will create a &lt;code&gt;loading&lt;/code&gt; property in our button component and assign it a default value of &lt;code&gt;false&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@props(['loading' =&amp;gt; false])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can read the Livewire Attributes inside our Blade Component using below code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$attributes-&amp;gt;wire('click')-&amp;gt;value()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can read more about them in the &lt;a href="https://laravel-livewire.com/docs/2.x/alpine-js#livewire-directives-from-blade-components"&gt;Livewire Docs.&lt;br&gt;
&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When both &lt;code&gt;loading&lt;/code&gt; property is present and the &lt;code&gt;wire:click&lt;/code&gt; attribute is present, we want to insert our span tags, otherwise we will just display the Slot. So our Blade Components becomes like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@props(['loading' =&amp;gt; false])

&amp;lt;button {{ $attributes-&amp;gt;merge(['type' =&amp;gt; 'submit']) }}&amp;gt;
    @if ($loading &amp;amp;&amp;amp; $target = $attributes-&amp;gt;wire('click')-&amp;gt;value())
        &amp;lt;span wire:loading.remove wire:target="{{$target}}"&amp;gt;{{$slot}}&amp;lt;/span&amp;gt;
        &amp;lt;span wire:loading wire:target="{{$target}}"&amp;gt;{{$loading}}&amp;lt;/span&amp;gt;
    @else
        {{ $slot }} 
    @endif
&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So now we can use our Button Component using the loading attributes as well as without the loading attribute.&lt;/p&gt;

&lt;p&gt;Hope you have enjoyed this tutorial. For similar articles, you can follow me on &lt;a href="https://twitter.com/TheLaravelDev"&gt;Twitter&lt;/a&gt;&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>livewire</category>
    </item>
    <item>
      <title>Laravel Components to keep your Code Clean</title>
      <dc:creator>Saurabh Mahajan</dc:creator>
      <pubDate>Wed, 12 Jan 2022 08:45:41 +0000</pubDate>
      <link>https://dev.to/100r0bh/laravel-components-to-keep-your-code-clean-3c22</link>
      <guid>https://dev.to/100r0bh/laravel-components-to-keep-your-code-clean-3c22</guid>
      <description>&lt;p&gt;In one of our recent Project, we had to create a lot of Forms using Livewire. The Forms were rather simple as can be seen from the following screenshot. The Forms were built on top of Laravel Breeze which comes up with some handy components for Form. However, even after using these Components, the View File had a lot of repeating HTML.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--apazSNSr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/http://www.ascsoftwares.com/wp-content/uploads/2022/01/add-form.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--apazSNSr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/http://www.ascsoftwares.com/wp-content/uploads/2022/01/add-form.png" alt="Preview" width="880" height="594"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Our View File looked like below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--kDkZF0WD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/http://www.ascsoftwares.com/wp-content/uploads/2022/01/add-form-html-1024x724.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--kDkZF0WD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/http://www.ascsoftwares.com/wp-content/uploads/2022/01/add-form-html-1024x724.png" alt="Preview" width="880" height="622"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see even with after using the Components for Label, Input and Error Message, there is still a lot of HTML which is just repeating with minor changes for each field. We decided to further organize the things by creating a Separate Component for Input Field Group which would consist of a div and then the Label, Text Input and the Error Field Component.&lt;/p&gt;

&lt;p&gt;We created a folder &lt;code&gt;form-group&lt;/code&gt; inside the &lt;code&gt;resources/views/components&lt;/code&gt; Folder. And within that we created a file input.blade.php.  We noticed that for each Input Form Group only label and the name are different. So we created them as &lt;code&gt;@props&lt;/code&gt; in our Component. Our File looked like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@props(['label', 'field'])

&amp;lt;div class="mt-4"&amp;gt;
    &amp;lt;x-label&amp;gt;{{$label}}&amp;lt;/x-label&amp;gt;
    &amp;lt;x-input class="block mt-1 w-1/2" type="text" wire:model.defer="{{$field}}" /&amp;gt;
    @error($field) &amp;lt;x-error-message&amp;gt;{{$message}}&amp;lt;/x-error-message&amp;gt; @enderror
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So now in order to display the Name Field all we had to use the above component and pass the props as below&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;x-form-group.input label="Name" field="product.name" /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By creating similar Form Group Components for Select, Textarea and other fields we were able to reduce our View File as below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--lcOPW6Cl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/http://www.ascsoftwares.com/wp-content/uploads/2022/01/add-form-formatted-html-1024x292.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--lcOPW6Cl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/http://www.ascsoftwares.com/wp-content/uploads/2022/01/add-form-formatted-html-1024x292.png" alt="Preview" width="880" height="251"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This looks much more compact and easy to read with all the noise being removed. Depending upon the requirements, we can easily make the components defined under &lt;code&gt;form-group&lt;/code&gt; to accept attributes and make more dynamic.&lt;/p&gt;

&lt;p&gt;Hope you have enjoyed this Article. Let us know in comments, how you use Components to keep your View File Clean. For similar articles, you can follow me on &lt;a href="https://twitter.com/TheLaravelDev"&gt;Twitter&lt;/a&gt;&lt;/p&gt;

</description>
      <category>laravel</category>
    </item>
    <item>
      <title>Tabs using Tailwind and AlpineJs</title>
      <dc:creator>Saurabh Mahajan</dc:creator>
      <pubDate>Wed, 05 Jan 2022 10:04:20 +0000</pubDate>
      <link>https://dev.to/100r0bh/tabs-using-tailwind-and-alpinejs-omg</link>
      <guid>https://dev.to/100r0bh/tabs-using-tailwind-and-alpinejs-omg</guid>
      <description>&lt;p&gt;In this tutorial, we are going to implement the Tab Component using Tailwind CSS and Alpine JS. Tutorial assumes that you have a basic understanding of both Tailwind CSS and JS and have them setup in a Project.&lt;/p&gt;

&lt;p&gt;We are going to have 3 Tabs each with its unique content. We will first of all define the Tabs. We are going to use &lt;code&gt;grid&lt;/code&gt; class. Since there are 3 tabs we will use &lt;code&gt;grid-cols-3&lt;/code&gt; class.&lt;/p&gt;

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

&amp;lt;div class="grid grid-cols-3 cursor-pointer font-bold"&amp;gt;
    &amp;lt;div&amp;gt;First&amp;lt;/div&amp;gt;
    &amp;lt;div&amp;gt;Second&amp;lt;/div&amp;gt;
    &amp;lt;div&amp;gt;Third&amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We have also used &lt;code&gt;cursor-pointer&lt;/code&gt; class so that the cursor changes to pointer and &lt;code&gt;font-bold&lt;/code&gt; class to make the Headings Bold. At this stage the Result looks like this.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/http%3A%2F%2Fwww.ascsoftwares.com%2Fwp-content%2Fuploads%2F2022%2F01%2Ftabs-1-1024x77.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/http%3A%2F%2Fwww.ascsoftwares.com%2Fwp-content%2Fuploads%2F2022%2F01%2Ftabs-1-1024x77.png" alt="Preview"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Next we will apply classes to these Tabs to design them. We will add &lt;code&gt;border&lt;/code&gt;, &lt;code&gt;border-black&lt;/code&gt;, &lt;code&gt;rounded-t-lg&lt;/code&gt; and &lt;code&gt;px-4&lt;/code&gt; classes to each of these div. The first 2 classes apply black border. &lt;code&gt;rounded-t-lg&lt;/code&gt; makes sure that the upper left and upper right corners of the div are rounded. &lt;code&gt;px-4&lt;/code&gt; just applies some left and right padding. At this stage our HTML and output looks like below:&lt;/p&gt;

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

&amp;lt;div class="grid grid-cols-3 cursor-pointer font-bold"&amp;gt;
    &amp;lt;div class="border border-black rounded-t-lg px-4"&amp;gt;First&amp;lt;/div&amp;gt;
    &amp;lt;div class="border border-black rounded-t-lg px-4"&amp;gt;Second&amp;lt;/div&amp;gt;
    &amp;lt;div class="border border-black rounded-t-lg px-4"&amp;gt;Third&amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/http%3A%2F%2Fwww.ascsoftwares.com%2Fwp-content%2Fuploads%2F2022%2F01%2Ftabs-2-1024x77.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/http%3A%2F%2Fwww.ascsoftwares.com%2Fwp-content%2Fuploads%2F2022%2F01%2Ftabs-2-1024x77.png" alt="Preview"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Next we will apply white background and blue text to the first tab, which would be active by default. We will use &lt;code&gt;bg-white&lt;/code&gt; and &lt;code&gt;text-blue-700&lt;/code&gt; classes for it. For inactive Tabs, we will use blue background and white text using the classes &lt;code&gt;bg-blue-700&lt;/code&gt; and &lt;code&gt;text-white&lt;/code&gt;.&lt;/p&gt;

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

&amp;lt;div class="grid grid-cols-3 cursor-pointer font-bold"&amp;gt;
    &amp;lt;div class="border border-black rounded-t-lg px-4 bg-white text-blue-700"&amp;gt;First&amp;lt;/div&amp;gt;
    &amp;lt;div class="border border-black rounded-t-lg px-4 bg-blue-700 text-white"&amp;gt;Second&amp;lt;/div&amp;gt;
    &amp;lt;div class="border border-black rounded-t-lg px-4 bg-blue-700 text-white"&amp;gt;Third&amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/http%3A%2F%2Fwww.ascsoftwares.com%2Fwp-content%2Fuploads%2F2022%2F01%2Ftabs-3-1024x77.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/http%3A%2F%2Fwww.ascsoftwares.com%2Fwp-content%2Fuploads%2F2022%2F01%2Ftabs-3-1024x77.png" alt="Preview"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Before we continue further, lets also include AlpineJS. We will wrap the above HTML in a div.&lt;/p&gt;

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

&amp;lt;div x-data="tabs"&amp;gt;
    ....
&amp;lt;/div&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here we have used &lt;code&gt;x-data&lt;/code&gt; and specified tabs. So we will need define this function. This function will hold all the properties and methods related to Tabs Component. &lt;/p&gt;

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

function tabs() {
    return {
        active: 1,
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here we have defined the property &lt;code&gt;active&lt;/code&gt; which would define the active Tab and we have given it a default value of 1. We would also define a method which would tell us if the given Tab is active or not.&lt;/p&gt;

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

function tabs() {
    return {
        active: 1,
        isActive(tab) {
            return tab == this.active;
        },
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next we will use this &lt;code&gt;isActive&lt;/code&gt; Method and &lt;code&gt;:class&lt;/code&gt; Alpine Directive to dynamically apply classes to our Tabs.&lt;/p&gt;

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

&amp;lt;div class="border border-black rounded-t-lg px-4"
    :class="isActive(1) ? 'bg-white text-blue-700': 'bg-blue-700 text-white'"
&amp;gt;First&amp;lt;/div&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Overall HTML looks like below. &lt;/p&gt;

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

&amp;lt;div x-data="tabs"&amp;gt;
    &amp;lt;div class="grid grid-cols-3 cursor-pointer font-bold"&amp;gt;
        &amp;lt;div class="border border-black rounded-t-lg px-4"
            :class="isActive(1) ? 'bg-white text-blue-700': 'bg-blue-700 text-white'"
        &amp;gt;First&amp;lt;/div&amp;gt;
        &amp;lt;div class="border border-black rounded-t-lg px-4"
            :class="isActive(2) ? 'bg-white text-blue-700': 'bg-blue-700 text-white'"
        &amp;gt;Second&amp;lt;/div&amp;gt;
        &amp;lt;div class="border border-black rounded-t-lg px-4"
            :class="isActive(3) ? 'bg-white text-blue-700': 'bg-blue-700 text-white'"
        &amp;gt;Third&amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next we will change the value of &lt;code&gt;active&lt;/code&gt; property when User Clicks on it. We will define a &lt;code&gt;setActive&lt;/code&gt; Method in JS.&lt;/p&gt;

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

    setActive(value) {
        this.active = value;
    }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We will call this method when User clicks on the Tab. We are going to use &lt;code&gt;@click&lt;/code&gt; Alpine Directive.&lt;/p&gt;

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

&amp;lt;div class="border border-black rounded-t-lg px-4"
    :class="isActive(1) ? 'bg-white text-blue-700': 'bg-blue-700 text-white'"
    @click="setActive(1)"
&amp;gt;First&amp;lt;/div&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;At this stage User should be able to change the Tab by clicking on it and the Active Tab Classes should change accordingly. Next we will define the Contents of the Tab.&lt;/p&gt;

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

&amp;lt;div class="border border-black p-4 rounded-b-lg"&amp;gt;
    &amp;lt;div&amp;gt;
        This is First Tab.
    &amp;lt;/div&amp;gt;
    &amp;lt;div&amp;gt;
        This is Second Tab.
    &amp;lt;/div&amp;gt;
    &amp;lt;div&amp;gt;
        This is Tab Tab.
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Currently all Contents are showing. We can show / hide the contents based on the active tab. We will use the &lt;code&gt;x-show&lt;/code&gt; directive and the same &lt;code&gt;isActive&lt;/code&gt; Method.&lt;/p&gt;

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

&amp;lt;div x-show="isActive(1)"&amp;gt;
    This is First Tab.
&amp;lt;/div&amp;gt;
&amp;lt;div x-show="isActive(2)"&amp;gt;
    This is Second Tab.
&amp;lt;/div&amp;gt;
&amp;lt;div x-show="isActive(3)"&amp;gt;
    This is Third Tab.
&amp;lt;/div&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;At this stage, our Tab Functionality will be working correctly. We can further improve UI this using the &lt;code&gt;x-transition&lt;/code&gt; directive.&lt;/p&gt;

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

&amp;lt;div x-show="isActive(1)" x-transition&amp;gt;
    This is First Tab.
&amp;lt;/div&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You will see that this gives a bit of flicker effect. We can fix it by changing &lt;code&gt;x-transition&lt;/code&gt; to &lt;code&gt;x-transition:enter.duration.500ms&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Our HTML at this stage looks like below:&lt;/p&gt;

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

&amp;lt;div x-data="tabs"&amp;gt;
    &amp;lt;div class="grid grid-cols-3 cursor-pointer font-bold"&amp;gt;
        &amp;lt;div class="border border-black rounded-t-lg px-4"
            :class="isActive(1) ? 'bg-white text-blue-700': 'bg-blue-700 text-white'"
            @click="setActive(1)"
        &amp;gt;First&amp;lt;/div&amp;gt;
        &amp;lt;div class="border border-black rounded-t-lg px-4"
            :class="isActive(2) ? 'bg-white text-blue-700': 'bg-blue-700 text-white'"
            @click="setActive(2)"
        &amp;gt;Second&amp;lt;/div&amp;gt;
        &amp;lt;div class="border border-black rounded-t-lg px-4"
            :class="isActive(3) ? 'bg-white text-blue-700': 'bg-blue-700 text-white'"
            @click="setActive(3)"
        &amp;gt;Third&amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;div class="border border-black p-4 rounded-b-lg"&amp;gt;
        &amp;lt;div x-show="isActive(1)" x-transition:enter.duration.500ms&amp;gt;
            This is First Tab.
        &amp;lt;/div&amp;gt;
        &amp;lt;div x-show="isActive(2)" x-transition:enter.duration.500ms&amp;gt;
            This is Second Tab.
        &amp;lt;/div&amp;gt;
        &amp;lt;div x-show="isActive(3)" x-transition:enter.duration.500ms&amp;gt;
            This is Third Tab.
        &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We see a bit of duplicating classes for Active Tab. We can define a &lt;code&gt;getClasses&lt;/code&gt; method as below:&lt;/p&gt;

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

getClasses(tab) {
    if(this.isActive(tab)) {
        return 'bg-white text-blue-700';
    }
    return 'bg-blue-700 text-white';
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Our HTML now becomes&lt;/p&gt;

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

&amp;lt;div x-data="tabs"&amp;gt;
    &amp;lt;div class="grid grid-cols-3 cursor-pointer font-bold"&amp;gt;
        &amp;lt;div class="border border-black rounded-t-lg px-4" :class="getClasses(1)"
            @click="setActive(1)"&amp;gt;First&amp;lt;/div&amp;gt;
        &amp;lt;div class="border border-black rounded-t-lg px-4" :class="getClasses(2)"
            @click="setActive(2)"&amp;gt;Second&amp;lt;/div&amp;gt;
        &amp;lt;div class="border border-black rounded-t-lg px-4" :class="getClasses(2)"
            @click="setActive(3)"&amp;gt;Third&amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;div class="border border-black p-4 rounded-b-lg"&amp;gt;
        &amp;lt;div x-show="isActive(1)" x-transition:enter.duration.500ms&amp;gt;
            This is First Tab.
        &amp;lt;/div&amp;gt;
        &amp;lt;div x-show="isActive(2)" x-transition:enter.duration.500ms&amp;gt;
            This is Second Tab.
        &amp;lt;/div&amp;gt;
        &amp;lt;div x-show="isActive(3)" x-transition:enter.duration.500ms&amp;gt;
            This is Third Tab.
        &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And our Tab should be working fine like below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/http%3A%2F%2Fwww.ascsoftwares.com%2Fwp-content%2Fuploads%2F2022%2F01%2Ftabs-4-1024x103.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/http%3A%2F%2Fwww.ascsoftwares.com%2Fwp-content%2Fuploads%2F2022%2F01%2Ftabs-4-1024x103.png" alt="Preview"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hope you have enjoyed this Article. For similar articles, you can follow me on &lt;a href="https://twitter.com/TheLaravelDev" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt;&lt;/p&gt;

</description>
      <category>tailwindcss</category>
      <category>alpinejs</category>
    </item>
    <item>
      <title>Applying Filter using BelongsToMany Relationship in Livewire</title>
      <dc:creator>Saurabh Mahajan</dc:creator>
      <pubDate>Wed, 06 Oct 2021 08:50:22 +0000</pubDate>
      <link>https://dev.to/100r0bh/applying-filter-on-a-belongstomany-column-using-livewire-1i63</link>
      <guid>https://dev.to/100r0bh/applying-filter-on-a-belongstomany-column-using-livewire-1i63</guid>
      <description>&lt;p&gt;In this Tutorial, we will see how to Filter Records using a BelongsToMany Relationship in Livewire. This is the part 6 of the Series related to adding New Functionality to a Table using Livewire. In &lt;a href="https://dev.to/100r0bh/applying-belongsto-filter-to-table-using-livewire-1elp"&gt;Last Part&lt;/a&gt; of the Series we implemented Filter on the BelongsTo column of the Product Model using Livewire.&lt;/p&gt;

&lt;p&gt;Lets say our Product Model has &lt;code&gt;belongsToMany&lt;/code&gt; Relationship with Category as follows&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public function categories()
    {
        return $this-&amp;gt;belongsToMany(Category::class);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That means there is a Category Table which holds all the Categories. And then there is a Pivot Table which links Products and Categories. And we want to Filter using Category, so when the User selects a Category we will display only those Products which are related to that Category.&lt;/p&gt;

&lt;p&gt;First of all we will fetch all the Categories. We would create a &lt;code&gt;categories&lt;/code&gt; property and populate it in the mount method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$this-&amp;gt;categories = Category::pluck('name', 'id')-&amp;gt;toArray();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And in the View, we would create the dropdown by looping through these &lt;code&gt;categories&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div&amp;gt;
    &amp;lt;label&amp;gt;
        Categories
    &amp;lt;/label&amp;gt;
    &amp;lt;select&amp;gt;
        &amp;lt;option value=""&amp;gt;Any&amp;lt;/option&amp;gt;
        @foreach($categories as $category_id =&amp;gt; $category_name)
        &amp;lt;option value="{{$category_id}}"&amp;gt;{{$category_name}}&amp;lt;/option&amp;gt;
        @endforeach
    &amp;lt;/select&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Dropdown will have all the Categories that User can select from. As usual we also have an &lt;code&gt;Any&lt;/code&gt; option so as to display all the Products.&lt;/p&gt;

&lt;p&gt;Next we will create a property called &lt;code&gt;$selectedCategory&lt;/code&gt; and link it with above dropdown using &lt;code&gt;wire:model&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;select wire:model="selectedCategory"&amp;gt;
    ....
    ....
&amp;lt;/select&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This way whenever User changes the above Dropdown, the property &lt;code&gt;$selectedCategory&lt;/code&gt; would be updated in the Component and Livewire will re-render the component. Now all we need to do is to change the Query to reflect the value of Selected Category.&lt;/p&gt;

&lt;p&gt;Below is the current Query that we have.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function query()
{
    return Product::query()
        -&amp;gt;when($this-&amp;gt;selectedStatus, function($query) {
            return $query-&amp;gt;where('status', $this-&amp;gt;selectedStatus);
        })
        -&amp;gt;when($this-&amp;gt;selectedBrand, function($query) {
            return $query-&amp;gt;where('brand_id', $this-&amp;gt;selectedBrand);
        });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will include another &lt;code&gt;when&lt;/code&gt; Condition and we would filter the records using &lt;code&gt;whereHas&lt;/code&gt; Clause like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-&amp;gt;when($this-&amp;gt;selectedCategory, function($query) {
    return $query-&amp;gt;whereHas('categories', function($query) {
        return $query-&amp;gt;where('categories.id', $this-&amp;gt;selectedCategory);
    });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Go ahead and test it, our Filter should be working now. So unlike the previous Filters where we were able to apply the Query directly on the &lt;code&gt;Product Model&lt;/code&gt;, here we had to pass a Closure to &lt;code&gt;whereHas&lt;/code&gt; in order to Filter using &lt;code&gt;BelongsToMany&lt;/code&gt; Relation.&lt;/p&gt;

&lt;p&gt;If you have liked this Tutorial, please checkout the Livewire Package &lt;a href="https://github.com/ascsoftw/tall-crud-generator"&gt;tall-crud-generator&lt;/a&gt; which automatically generates all the Code related to applying Filter on a BelongsToMany Relation.  &lt;/p&gt;

</description>
      <category>laravel</category>
      <category>livewire</category>
    </item>
    <item>
      <title>Applying Filter on a BelongsTo Column using Livewire</title>
      <dc:creator>Saurabh Mahajan</dc:creator>
      <pubDate>Thu, 30 Sep 2021 13:56:20 +0000</pubDate>
      <link>https://dev.to/100r0bh/applying-belongsto-filter-to-table-using-livewire-1elp</link>
      <guid>https://dev.to/100r0bh/applying-belongsto-filter-to-table-using-livewire-1elp</guid>
      <description>&lt;p&gt;In this Tutorial, we will see how to implement Filter on a belongsTo Column to a Table using Livewire. This is the part 5 of the Series related to adding New Functionality to a Table using Livewire. In &lt;a href="https://dev.to/100r0bh/applying-filter-to-table-using-livewire-1n8j"&gt;Last Part&lt;/a&gt; of the Series we implemented Filter on the &lt;code&gt;status&lt;/code&gt; column of the Product Model using Livewire.&lt;/p&gt;

&lt;p&gt;Lets say our Product Model has &lt;code&gt;belongsTo&lt;/code&gt; Relationship with Brand as follows&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public function brand()
    {
        return $this-&amp;gt;belongsTo(Brand::class);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That means our Product table has a column &lt;code&gt;brand_id&lt;/code&gt;. And we want to Filter the Result using this column. This is very similar to the Filter that we applied on the &lt;code&gt;status&lt;/code&gt; column in the last part. The only difference is that we would need to fetch the brands from the Brand table so that we can show them in the dropdown.&lt;/p&gt;

&lt;p&gt;We would create a &lt;code&gt;brands&lt;/code&gt; property and populate it in the mount method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$this-&amp;gt;brands = Brand::pluck('name', 'id')-&amp;gt;toArray();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And in the View, we would create the dropdown by looping through the &lt;code&gt;brands&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div&amp;gt;
    &amp;lt;label&amp;gt;
        Brand
    &amp;lt;/label&amp;gt;
    &amp;lt;select&amp;gt;
        &amp;lt;option value=""&amp;gt;Any&amp;lt;/option&amp;gt;
        @foreach($brands as $brand_id =&amp;gt; $brand_name)
        &amp;lt;option value="{{$brand_id}}"&amp;gt;{{$brand_name}}&amp;lt;/option&amp;gt;
        @endforeach
    &amp;lt;/select&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Dropdown will have all the Brands that User can select from. Moreover, we also have an &lt;code&gt;Any&lt;/code&gt; option so as to display all the Products.&lt;/p&gt;

&lt;p&gt;Next we will create a property called &lt;code&gt;$selectedBrand&lt;/code&gt; and link it with above dropdown using &lt;code&gt;wire:model&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public $selectedBrand = '';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;select wire:model="selectedBrand"&amp;gt;
    &amp;lt;option value=""&amp;gt;Any&amp;lt;/option&amp;gt;
    @foreach($brands as $brand_id =&amp;gt; $brand_name)
    &amp;lt;option value="{{$brand_id}}"&amp;gt;{{$brand_name}}&amp;lt;/option&amp;gt;
    @endforeach
&amp;lt;/select&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This way whenever User changes the above Dropdown, the property &lt;code&gt;$selectedBrand&lt;/code&gt; would be updated in the Component and Livewire will re-render the component. Now all we need to do is to change the Query so that User Selection is honoured.&lt;/p&gt;

&lt;p&gt;Below is the current Query that we have.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function query()
{
    return Product::query()
        -&amp;gt;when($this-&amp;gt;selectedStatus, function($query) {
            return $query-&amp;gt;where('status', $this-&amp;gt;selectedStatus);
        });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will include another &lt;code&gt;when&lt;/code&gt; Condition like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function query()
{
    return Product::query()
        -&amp;gt;when($this-&amp;gt;selectedStatus, function($query) {
            return $query-&amp;gt;where('status', $this-&amp;gt;selectedStatus);
        })
        -&amp;gt;when($this-&amp;gt;selectedBrand, function($query) {
            return $query-&amp;gt;where('brand_id', $this-&amp;gt;selectedBrand);
        });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since we are using &lt;code&gt;when&lt;/code&gt; clause, the query with where clause on &lt;code&gt;brand_id&lt;/code&gt; column will only be added when User selects a particular Brand. So if the User selects &lt;code&gt;Any&lt;/code&gt; which is equivalent to empty, then the query with where Clause on brand_id will not be added. &lt;/p&gt;

&lt;p&gt;This is all that we need to filter the Records using a BelongsTo column. If you have noticed this is very similar to the filter that we applied on the &lt;code&gt;status&lt;/code&gt; column. In the next &lt;a href="https://dev.to/100r0bh/applying-filter-on-a-belongstomany-column-using-livewire-1i63"&gt;post&lt;/a&gt; we will see how to filter the Records using BelongsToMany Relation.&lt;/p&gt;

&lt;p&gt;If you have liked this Tutorial, please checkout the Livewire Package &lt;a href="https://github.com/ascsoftw/tall-crud-generator"&gt;tall-crud-generator&lt;/a&gt; which automatically generates all the Code related to Filter on multiple columns. &lt;/p&gt;

</description>
      <category>laravel</category>
      <category>livewire</category>
    </item>
    <item>
      <title>Applying Filter to Table using Livewire</title>
      <dc:creator>Saurabh Mahajan</dc:creator>
      <pubDate>Fri, 24 Sep 2021 12:22:32 +0000</pubDate>
      <link>https://dev.to/100r0bh/applying-filter-to-table-using-livewire-1n8j</link>
      <guid>https://dev.to/100r0bh/applying-filter-to-table-using-livewire-1n8j</guid>
      <description>&lt;p&gt;In this Tutorial, we will see how to implement Filter on a Table using Livewire. This is the part 4 of the Series related to adding New Functionality to a Table using Livewire. In &lt;a href="https://dev.to/100r0bh/bulk-action-using-livewire-31i7"&gt;Last Part&lt;/a&gt; of the Series we saw how to implement Bulk Action using Livewire.&lt;/p&gt;

&lt;p&gt;Let us assume we have a Model called as &lt;code&gt;Product&lt;/code&gt; and it has a column &lt;code&gt;status&lt;/code&gt; which represents whether the Product is active or not. And we want to give User the ability so that they can Filter the Products using &lt;code&gt;status&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;I would assume that you already have a working Livewire Component which is showing the Records in a Table Form. First of all we are going to create a Dropdown in View which would allow User to Filter the Records.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div&amp;gt;
    &amp;lt;label&amp;gt;
        Status
    &amp;lt;/label&amp;gt;
    &amp;lt;select&amp;gt;
        &amp;lt;option value=""&amp;gt;Any&amp;lt;/option&amp;gt;
        &amp;lt;option value="1"&amp;gt;Yes&amp;lt;/option&amp;gt;
        &amp;lt;option value="2"&amp;gt;No&amp;lt;/option&amp;gt;
    &amp;lt;/select&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Dropdown has 3 Values. Any, Yes and No. When User selects Any, all Products will be displayed. When User selects Yes, only those Products which have &lt;code&gt;status&lt;/code&gt; of 1 should display. And when the User selects No, Products with &lt;code&gt;status&lt;/code&gt; of 0 will display.&lt;/p&gt;

&lt;p&gt;Next we will create a property called &lt;code&gt;$selectedStatus&lt;/code&gt; and link it with above dropdown using &lt;code&gt;wire:model&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public $selectedStatus = '';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;select wire:model="selectedStatus"&amp;gt;
    &amp;lt;option value=""&amp;gt;Any&amp;lt;/option&amp;gt;
    &amp;lt;option value="1"&amp;gt;Yes&amp;lt;/option&amp;gt;
    &amp;lt;option value="2"&amp;gt;No&amp;lt;/option&amp;gt;
&amp;lt;/select&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This way whenever User changes the above Dropdown, the property &lt;code&gt;$selectedStatus&lt;/code&gt; would be updated in the Component and Livewire will re-render the component. Now all we need to do is to change the Query so that User Selection is honoured.&lt;/p&gt;

&lt;p&gt;Below is the current Query that we have.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function query()
{
    return Product::query();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will change this using &lt;code&gt;when&lt;/code&gt; Condition like below&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function query()
{
    return Product::query()
        -&amp;gt;when($this-&amp;gt;selectedStatus, function($query) {
            return $query-&amp;gt;where('status', $this-&amp;gt;selectedStatus);
        });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since we are using &lt;code&gt;when&lt;/code&gt; clause, the query with where clause on &lt;code&gt;status&lt;/code&gt; column will only be added when User selects Yes or No. So if the User selects &lt;code&gt;Any&lt;/code&gt; which is equivalent to empty, then the query with where Clause will not be added. &lt;/p&gt;

&lt;p&gt;This is all that we need to filter the Records using Livewire. Here we filtered the Records using the column from the current table. In the next &lt;a href="https://dev.to/100r0bh/applying-belongsto-filter-to-table-using-livewire-1elp"&gt;post&lt;/a&gt; we will see how to filter the Records using Belongs To Relation.&lt;/p&gt;

&lt;p&gt;If you have liked this Tutorial, please checkout the Livewire Package &lt;a href="https://github.com/ascsoftw/tall-crud-generator"&gt;tall-crud-generator&lt;/a&gt; which automatically generates all the Code related to Filter on multiple columns.  &lt;/p&gt;

</description>
      <category>laravel</category>
      <category>livewire</category>
    </item>
    <item>
      <title>Bulk Action using Livewire</title>
      <dc:creator>Saurabh Mahajan</dc:creator>
      <pubDate>Wed, 22 Sep 2021 11:11:00 +0000</pubDate>
      <link>https://dev.to/100r0bh/bulk-action-using-livewire-31i7</link>
      <guid>https://dev.to/100r0bh/bulk-action-using-livewire-31i7</guid>
      <description>&lt;p&gt;In this Tutorial, we will see how to implement Bulk Action so that User can select and update multiple records using Livewire. This is the part 3 of the Series related to Livewire Table. In &lt;a href="https://dev.to/100r0bh/hide-show-columns-in-livewire-table-1fgb"&gt;Part 2&lt;/a&gt; of the Series we saw how to Hide/Show Columns in a Table using Livewire.&lt;/p&gt;

&lt;p&gt;Let us assume we have a Model called as &lt;code&gt;Product&lt;/code&gt; and it has a column &lt;code&gt;status&lt;/code&gt;. We want to give user the ability to select multiple products and then change the value of &lt;code&gt;status&lt;/code&gt; column for all of the selected products.&lt;/p&gt;

&lt;p&gt;I would assume that you already have a working Livewire Component which is showing the Records in a Table Form. First of all we are going to add a New Property &lt;code&gt;$selectedProducts&lt;/code&gt; to our Livewire Component.  This would hold all the Products that user has selected.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public $selectedProducts = [];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now in the View, we would like to display a checkbox next to each item. We would create a New column and we will paste the following code inside the loop which displays all the Results.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;input type="checkbox" value="{{$product-&amp;gt;id}}" /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This would display the checkbox and we have given it the value which is the Primary Key of the Product Table so as to uniquely identify it.&lt;/p&gt;

&lt;p&gt;Now we would link this checkbox to the &lt;code&gt;$selectedProducts&lt;/code&gt; using the &lt;code&gt;wire:model&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;input type="checkbox" value="{{$product-&amp;gt;id}}"
     wire:model="selectedProducts" /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now every time a User selects a Product, &lt;code&gt;$selectedProducts&lt;/code&gt; would be updated. So at any time &lt;code&gt;$selectedProducts&lt;/code&gt; would have all the Products that User has selected for Bulk Action.&lt;/p&gt;

&lt;p&gt;Infact, we are going to use &lt;code&gt;wire:model.defer&lt;/code&gt;. The &lt;code&gt;defer&lt;/code&gt; directives makes sure that our Component will not be re-rendered when the User checks the checkbox. This will result in a significant performance improvement. If you want to learn more about defer and other techniques to improve Performance using Livewire, you can check this &lt;a href="https://dev.to/100r0bh/3-tips-to-improve-livewire-performance-nnd"&gt;Article&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;input type="checkbox" value="{{$product-&amp;gt;id}}"
     wire:model.defer="selectedProducts" /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we need to create 2 Buttons, Activate and Deactivate. Both these buttons will call a method &lt;code&gt;changeStatus&lt;/code&gt; on click. We will pass the value that we want to set for the status column as the parameter. So for Activate we pass 1 and for Deactivate we will pass 0.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button wire:click="changeStatus(1)"&amp;gt;Activate&amp;lt;/button&amp;gt;
&amp;lt;button wire:click="changeStatus(0)"&amp;gt;Deactivate&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next we need to define this method within our Component. We can define it as follows. Here &lt;code&gt;$status&lt;/code&gt; will hold the value that we want to set for the status column. So for Activate it will be 1 and for Deactivate it will be 0.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function changeStatus($status)
{
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Within this method we will first of all check, if there are any Records that User has selected using &lt;code&gt;$selectedProducts&lt;/code&gt;. Then we will update the status column for all those Products. And then we will finally clear the &lt;code&gt;$selectedProducts&lt;/code&gt; variable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (!empty($this-&amp;gt;selectedProducts)) {
    Product::whereIn('id', $this-&amp;gt;selectedProducts)-&amp;gt;update(['status' =&amp;gt; $status]);
    $this-&amp;gt;selectedProducts = [];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And that is all we need to do to give User the Ability to update Records in Bulk.&lt;/p&gt;

&lt;p&gt;If you have liked this Tutorial, please checkout the Livewire Package &lt;a href="https://github.com/ascsoftw/tall-crud-generator"&gt;tall-crud-generator&lt;/a&gt; which automatically generates all the Code related to Bulk Actions.  &lt;/p&gt;

</description>
      <category>laravel</category>
      <category>livewire</category>
    </item>
  </channel>
</rss>
