<?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 Nick Basile on Medium]]></title>
        <description><![CDATA[Stories by Nick Basile on Medium]]></description>
        <link>https://medium.com/@nickjbasile?source=rss-12d3411267e9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HmgX-nrxpIUYU4DsDZ5GIg.jpeg</url>
            <title>Stories by Nick Basile on Medium</title>
            <link>https://medium.com/@nickjbasile?source=rss-12d3411267e9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 14:05:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nickjbasile/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[Improving Our Laravel Nova CRM]]></title>
            <link>https://nickjbasile.medium.com/improving-our-laravel-nova-crm-3098c74ae879?source=rss-12d3411267e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3098c74ae879</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[getting-started]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[nova]]></category>
            <dc:creator><![CDATA[Nick Basile]]></dc:creator>
            <pubDate>Sat, 25 Aug 2018 16:52:59 GMT</pubDate>
            <atom:updated>2018-12-04T15:37:03.037Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZ0d9KM7lRyMcz1i7dTFuA.jpeg" /></figure><p>In my <a href="https://nick-basile.com/blog/post/deep-diving-laravel-nova">last post</a>, we started building a simple CRM using Laravel Nova. It was pretty complete when we left it, but I think we can add a few more features and explore the rest of what Nova has to offer. In this walkthrough, we’ll take a look at how to use Nova’s Actions and authorization.</p><h3>Set Up</h3><p>If you’re brand new to Nova, I recommend checking out my <a href="https://nick-basile.com/blog/post/getting-started-with-laravel-nova">“Getting Started With Laravel Nova”</a> post where I explained in detail how to install and set up Nova on your machine. For this walkthrough, I’m going to assume that you’ve followed along with the <a href="https://nick-basile.com/blog/post/deep-diving-laravel-nova">previous CRM post</a>. So, you should be able to log in and see this screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N0IRJeag-dqEjI96.png" /></figure><h3>Improving Our CRM</h3><p>First up, let’s add a Nova Action to our CRM. Actions let us perform updates and other pre-defined activities straight from our index page. This is great because we don’t have to drop into the edit page to make changes, and we’re even able to do mass updates to lots of records at once!</p><h3>Actions</h3><p>For our CRM, it would be great if we could update our Leads’ statuses directly from the index page. That way our sales team could quickly manage the Leads as they’re making sales calls.</p><p>To start, we’ll use the Nova cli generator to spin up an Action for us using the following command.</p><pre>php artisan nova:action UpdateLeadStatus</pre><p>This command creates an Actions directory inside our app\Nova directory and places our Action file inside of it. Our generated UpdateLeadStatus.php file looks like this:</p><pre>&lt;?php</pre><pre>namespace App\Nova\Actions;</pre><pre>use Illuminate\Bus\Queueable;<br>use Laravel\Nova\Actions\Action;<br>use Illuminate\Support\Collection;<br>use Laravel\Nova\Fields\ActionFields;<br>use Illuminate\Queue\SerializesModels;<br>use Illuminate\Queue\InteractsWithQueue;<br>use Illuminate\Contracts\Queue\ShouldQueue;</pre><pre>class UpdateLeadStatus extends Action<br>{<br>    use InteractsWithQueue, Queueable, SerializesModels;</pre><pre>    /**<br>     * Perform the action on the given models.<br>     *<br>     * @param  \Laravel\Nova\Fields\ActionFields  $fields<br>     * @param  \Illuminate\Support\Collection  $models<br>     * @return mixed<br>     */<br>    public function handle(ActionFields $fields, Collection $models)<br>    {<br>        //<br>    }</pre><pre>    /**<br>     * Get the fields available on the action.<br>     *<br>     * @return array<br>     */<br>    public function fields()<br>    {<br>        return [];<br>    }<br>}</pre><p>As you can see, we have a handle() and fields() methods provided for us. The fields() method let us prompt the user for data when the initiate the action in the UI, and the handle() method is where we&#39;ll be writing the logic that completes the action.</p><p>Let’s define our fields() first so we can use them in the handle(). In our case, we&#39;d like to ask the user which status they want the Lead to have. So to do that, we can use the same code that we used in our Lead Resource.</p><pre>public function fields()<br>{<br>    return [<br>        Select::make(&#39;Status&#39;)<br>            -&gt;options(\App\Lead::getStatuses()),<br>    ];<br>}</pre><p>Now, that we can receive the user’s status selection, we can code out our handle() method.</p><pre>public function handle(ActionFields $fields, Collection $models)<br>{<br>    foreach ($models as $model) {<br>        $model-&gt;status = $fields-&gt;status;<br>        $model-&gt;save();<br>    }<br>}</pre><p>In our handle(), we&#39;re iterating over all of the $models, setting the $model&#39;s status to what is selecting in the UI, and then saving the $model. We need to make sure we iterate over the $models because it is always provided as a collection, even if only one model is being updated.</p><p>Now that our Action is finished, we can register it in our Lead Resource and see it in the UI.</p><pre>public function actions(Request $request)<br>{<br>    return [<br>        new Actions\UpdateLeadStatus,<br>    ];<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*10Zoy3Kh3JAzytmy.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*plaIRAEOEnHNYyEZ.png" /></figure><p>When using Actions from the index page, it’s important to remember that the Actions will only appear after you’ve selected a record to update. After I registered my Action for the first time, I spent a long time trying to figure out why it didn’t appear as the Lenses and Filters did.</p><p>We can also run Actions directly from our Lead’s view page. I can be this being super useful if you found a Lead via the search bar and needed to run a custom Action on them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P0DlD48DSAyf5CTS.png" /></figure><p>Now that we have our Action in place let’s take move on to our CRM’s authorization.</p><h3>Authorization</h3><p>Ensuring that users can only interact with features that they have access to is a huge deal. In past projects, this is always a massive undertaking and critically important to its success. Fortunately, Nova makes this a breeze for us as well.</p><p>For our CRM, since this is an internal tool used by our team, we don’t have tons of access issues to deal with. However, let’s make sure that only our Admin users can delete Leads, Users, and Notes.</p><p>First, we’ll need to add an isAdmin() method to our User Model so we can check if a given user is an Admin. You could store this in the database, or use a package like Spatie&#39;s <a href="https://github.com/spatie/laravel-permission">laravel-permissions</a>. However, for this simple project, we&#39;ll just hard code it.</p><pre>public function isAdmin()<br>{<br>    $admin_emails = [<br>        &#39;&lt;your-user-email&gt;&#39;<br>    ];</pre><pre>    return in_array($this-&gt;email, $admin_emails);<br>}</pre><p>Now that we have our access requirements in place, we can start setting up our Authorization. Out-of-the-box, Nova is set up to work with <a href="https://laravel.com/docs/5.6/authorization#creating-policies">Laravel’s Policies</a>.</p><p>From the docs, “Policies are classes that organize authorization logic around a particular model or resource. For example, if your application is a blog, you may have a Post model and a corresponding PostPolicy to authorize user actions such as creating or updating posts.&quot;</p><p>Nova is smart enough to pick up on the policies we’ve defined and use them to lock down our admin section. So, let’s generate our Policies and implement our authorization logic.</p><p>To start, we’ll use php artisan to spin up some Policies.</p><pre>php artisan make:policy UserPolicy -m User &amp;&amp; php artisan make:policy LeadPolicy -m Lead &amp;&amp; php artisan make:policy NotePolicy -m Note</pre><p>Now we need to register them in our AuthServiceProvider.php.</p><pre>protected $policies = [<br>    &#39;App\User&#39; =&gt; &#39;App\Policies\UserPolicy&#39;,<br>    &#39;App\Lead&#39; =&gt; &#39;App\Policies\LeadPolicy&#39;,<br>    &#39;App\Note&#39; =&gt; &#39;App\Policies\NotePolicy&#39;,<br>];</pre><p>With the Policies registered, we can run through all of the pre-generated methods and define our access logic.</p><pre>public function view(User $user, &lt;model&gt; $model)<br>{<br>    return true;<br>}</pre><pre>public function create(User $user)<br>{<br>    return true;<br>}</pre><pre>public function update(User $user, &lt;model&gt; $model)<br>{<br>    return true;<br>}</pre><pre>public function delete(User $user, &lt;model&gt; $model)<br>{<br>    return $user-&gt;isAdmin();<br>}</pre><pre>public function restore(User $user, &lt;model&gt; $model)<br>{<br>    return $user-&gt;isAdmin();<br>}</pre><pre>public function forceDelete(User $user, &lt;model&gt; $model)<br>{<br>    return $user-&gt;isAdmin();<br>}</pre><p>Just like that, we’re only allowing Admin users to delete our models. If we take a look at the Admin as another user, we’ll notice that all of the delete buttons have been removed from the UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9hPR1_ooHuCRwUhI.png" /></figure><h3>The Wrap-Up</h3><p>Once again, we’ve seen how quick and easy it is to use Nova to implement features that would have taken significant engineering efforts in the past. I hope these walkthroughs have given you a baseline understanding of how to use Nova, and I can’t wait to see what we’ll build next! As always, feel free to ask me any questions on <a href="https://twitter.com/nickjbasile">Twitter</a>. And until next time, happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3098c74ae879" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Diving Laravel Nova]]></title>
            <link>https://nickjbasile.medium.com/deep-diving-laravel-nova-6eb413a081ee?source=rss-12d3411267e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eb413a081ee</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[laravel-nova]]></category>
            <category><![CDATA[getting-started]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Nick Basile]]></dc:creator>
            <pubDate>Thu, 23 Aug 2018 04:10:57 GMT</pubDate>
            <atom:updated>2018-12-04T15:36:51.270Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4O5_yNe3IY9wT9HPu9cFrQ.jpeg" /></figure><p>In my <a href="https://nick-basile.com/blog/post/getting-started-with-laravel-nova">previous post</a>, we saw how to get started with Nova and use it to create a simple blog. While that’s a nice “Hello World” example, I’d like to explore more of Nova’s features and get a better feel for using it.</p><p>So, for this deep dive, let’s build a very light CRM that lets us capture and manage leads. In the process, we’ll take a look at how to use Nova’s metrics; customize the search bar, and figure out filters and lenses.</p><p>Let’s dive right in!</p><h3>Getting Started</h3><p>If you’re brand new to Nova, I recommend checking out my <a href="https://nick-basile.com/blog/post/getting-started-with-laravel-nova">previous post</a> where I explained in detail how to install and set up Nova on your machine. For this walkthrough, I’m going to assume that we have Nova installed in a fresh Laravel project. So, you should be able to log in and see this screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aeTnpM-wTQP5IAnL.png" /></figure><h3>Visitor Submissions</h3><p>Before we dive into the Nova side of things, we’ll need to scaffold out our models like we always do with Laravel. For our CRM, let’s work with two models to start.</p><p>We’ll have a Lead model which we’ll use to keep track of all the visitors interacting with us. Also, let’s have a Note model, so our admin users can leave notes for themselves about the Leads. So, for our relationship, our Leads will have many Notes, and our Users will have many Notes as well.</p><p>Let’s start building these models by running, php artisan make:model Lead -aand php artisan make:model Note -a from our terminal.</p><h3>Migrations</h3><p>With these files added, we can jump into the migrations and add our columns. Our Lead migration will look like this:</p><pre>public function up()<br>{<br>    Schema::create(&#39;leads&#39;, function (Blueprint $table) {<br>        $table-&gt;increments(&#39;id&#39;);<br>        $table-&gt;text(&#39;type&#39;);<br>        $table-&gt;text(&#39;status&#39;);<br>        $table-&gt;text(&#39;first_name&#39;);<br>        $table-&gt;text(&#39;last_name&#39;);<br>        $table-&gt;text(&#39;full_name&#39;);<br>        $table-&gt;text(&#39;email&#39;);<br>        $table-&gt;timestamps();<br>    });<br>}</pre><p>Then our Note migration will look like this:</p><pre>public function up()<br>{<br>    Schema::create(&#39;notes&#39;, function (Blueprint $table) {<br>        $table-&gt;increments(&#39;id&#39;);<br>        $table-&gt;integer(&#39;user_id&#39;);<br>        $table-&gt;integer(&#39;lead_id&#39;);<br>        $table-&gt;text(&#39;priority&#39;);<br>        $table-&gt;text(&#39;title&#39;);<br>        $table-&gt;text(&#39;body&#39;);<br>        $table-&gt;timestamps();<br>    });<br>}</pre><p>Now we can run php artisan migrate to add those tables to our database. With that taken care of, let&#39;s define our relationships on the models.</p><h3>Models</h3><p>If we recall, we said that our Notes model would have many Leads and Users, so let’s set up those relationships first. In Note.php, we can add the following:</p><pre>class Note extends Model<br>{<br>    public function user()<br>    {<br>        return $this-&gt;belongsTo(&#39;App\User&#39;);<br>    }</pre><pre>    public function lead()<br>    {<br>        return $this-&gt;belongsTo(&#39;App\Lead&#39;);<br>    }<br>}</pre><p>Then, inside of User.php and Lead.php, we can add our Notes relationship like this:</p><pre>//User.php<br>class User extends Authenticatable<br>{<br>    use Notifiable;</pre><pre>    /**<br>     * The attributes that are mass assignable.<br>     *<br>     * @var array<br>     */<br>    protected $fillable = [<br>        &#39;name&#39;, &#39;email&#39;, &#39;password&#39;,<br>    ];</pre><pre>    /**<br>     * The attributes that should be hidden for arrays.<br>     *<br>     * @var array<br>     */<br>    protected $hidden = [<br>        &#39;password&#39;, &#39;remember_token&#39;,<br>    ];</pre><pre>    public function notes()<br>    {<br>        return $this-&gt;hasMany(&#39;App\Note&#39;);<br>    }<br>}</pre><pre>//Lead.php<br>class Lead extends Model<br>{<br>    public function notes()<br>    {<br>        return $this-&gt;hasMany(&#39;App\Note&#39;);<br>    }<br>}</pre><p>Next, in our Lead model, we’ll need to define some $fillable attributes so our leads can provide their information. Let&#39;s also override the boot() method so we can generate the Lead&#39;s full_name from their first_name and last_nameattributes. So, inside of Lead.php, we&#39;ll have the following:</p><pre>class Lead extends Model<br>{<br>    protected $fillable = [<br>        &#39;type&#39;,<br>        &#39;status&#39;,<br>        &#39;first_name&#39;,<br>        &#39;last_name&#39;,<br>        &#39;full_name,<br>        &#39;email&#39;,<br>    ];<br>    <br>    protected static function boot()<br>    {<br>        parent::boot();</pre><pre>        static::saving(function ($lead) {<br>            $lead-&gt;full_name = $lead-&gt;first_name . &#39; &#39; . $lead-&gt;last_name;<br>        });<br>    }</pre><pre>    public function notes()<br>    {<br>        return $this-&gt;hasMany(&#39;App\Note&#39;);<br>    }<br>}</pre><p>Finally, let’s provide some constants and helper methods in our Lead and Note models so we can easily access their type, status, and priority values. These helpers aren&#39;t strictly required, but I find it helpful to have these values defined up front, so I don&#39;t change them on a whim. So our models will look like this:</p><pre>//Note.php<br>class Note extends Model<br>{<br>    const LOW_PRIORITY = &#39;Low&#39;;<br>    const MEDIUM_PRIORITY = &#39;Medium&#39;;<br>    const HIGH_PRIORITY = &#39;High&#39;;</pre><pre>    public function user()<br>    {<br>        return $this-&gt;belongsTo(&#39;App\User&#39;);<br>    }</pre><pre>    public function lead()<br>    {<br>        return $this-&gt;belongsTo(&#39;App\Lead&#39;);<br>    }</pre><pre>    public static function getPriorities()<br>    {<br>        return [<br>            self::LOW_PRIORITY =&gt; self::LOW_PRIORITY,<br>            self::MEDIUM_PRIORITY =&gt; self::MEDIUM_PRIORITY,<br>            self::HIGH_PRIORITY =&gt; self::HIGH_PRIORITY,<br>        ];<br>    }<br>}</pre><pre>//Lead.php<br>class Lead extends Model<br>{<br>    const ORGANIC_TYPE = &#39;Organic&#39;;<br>    const USER_SUBMITTED_TYPE = &#39;User Submitted&#39;;</pre><pre>    const PROSPECT_STATUS = &#39;Prospect&#39;;<br>    const LEAD_STATUS = &#39;Lead&#39;;<br>    const CUSTOMER_STATUS = &#39;Customer&#39;;</pre><pre>    protected $fillable = [<br>        &#39;type&#39;,<br>        &#39;status&#39;,<br>        &#39;first_name&#39;,<br>        &#39;last_name&#39;,<br>        &#39;full_name&#39;,<br>        &#39;email&#39;,<br>    ];</pre><pre>    public function notes()<br>    {<br>        return $this-&gt;hasMany(&#39;App\Note&#39;);<br>    }</pre><pre>    public static function getTypes()<br>    {<br>        return [<br>            self::ORGANIC_TYPE =&gt; self::ORGANIC_TYPE,<br>            self::USER_SUBMITTED_TYPE =&gt; self::USER_SUBMITTED_TYPE,<br>        ];<br>    }</pre><pre>    public static function getStatuses()<br>    {<br>        return [<br>            self::PROSPECT_STATUS =&gt; self::PROSPECT_STATUS,<br>            self::LEAD_STATUS =&gt; self::LEAD_STATUS,<br>            self::CUSTOMER_STATUS =&gt; self::CUSTOMER_STATUS,<br>        ];<br>    }<br>}</pre><p>As I said, this approach helps me, and I hope it can help you out. If you don’t like it, feel free to ignore this part. That said, we’ll use these methods to help us keep our models in-sync with their Nova resources, so it won’t hurt to try it out.</p><p>Just like that, we’ve finished our models. Now, let’s create a quick form on the non-Nova side of our app so visitors can enter their details and become leads.</p><h3>Visitor Form</h3><p>To style our form, we’ll use Tailwind CSS’ CDN to get up and running quickly. We can keep using welcome.blade.php, and we&#39;ll clear out the default HTML and drop in the CDN.</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;{{ app()-&gt;getLocale() }}&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>    &lt;title&gt;Nova CRM Demo&lt;/title&gt;<br>    &lt;!-- Fonts --&gt;<br>    &lt;link href=&quot;https://fonts.googleapis.com/css?family=Nunito:200,600&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;&gt;<br>    &lt;!-- Styles --&gt;<br>    &lt;link href=&quot;https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css&quot; rel=&quot;stylesheet&quot;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;</pre><pre>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now let’s grab one of the example forms from the <a href="https://tailwindcss.com/docs/examples/forms">Tailwind docs</a> (thank you Adam et al!) and quickly spin up our form.</p><pre>&lt;body&gt;<br>    &lt;div class=&quot;flex flex-col items-center justify-center md:h-screen md:bg-blue-lightest&quot;&gt;<br>        &lt;form class=&quot;w-full max-w-md bg-white rounded p-10 md:shadow&quot; action=&quot;/form-submit&quot; method=&quot;POST&quot;&gt;<br>            &lt;h1 class=&quot;text-grey-darkest mb-8 text-center&quot;&gt;Sign Up For Our Nova App&lt;/h1&gt;<br>            {{ csrf_field() }}<br>            &lt;div class=&quot;flex flex-wrap -mx-3 mb-6&quot;&gt;<br>                &lt;div class=&quot;w-full md:w-1/2 px-3 mb-6 md:mb-0&quot;&gt;<br>                    &lt;label class=&quot;block uppercase tracking-wide text-grey-darker text-xs font-bold mb-2&quot; for=&quot;first-name&quot;&gt;<br>                        First Name<br>                    &lt;/label&gt;<br>                    &lt;input class=&quot;appearance-none block w-full bg-grey-lighter text-grey-darker border rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white {{ $errors-&gt;has(&#39;first_name&#39;) ? &#39;border-red mb-3&#39; : &#39;border-grey-lighter&#39; }}&quot; id=&quot;first_name&quot; name=&quot;first_name&quot; type=&quot;text&quot; placeholder=&quot;Jane&quot;&gt;<br>                    @if($errors-&gt;has(&#39;first_name&#39;))<br>                        &lt;p class=&quot;text-red text-xs italic&quot;&gt;{{ $errors-&gt;first(&#39;first_name&#39;) }}&lt;/p&gt;<br>                    @endif<br>                &lt;/div&gt;<br>                &lt;div class=&quot;w-full md:w-1/2 px-3&quot;&gt;<br>                    &lt;label class=&quot;block uppercase tracking-wide text-grey-darker text-xs font-bold mb-2&quot; for=&quot;last-name&quot;&gt;<br>                        Last Name<br>                    &lt;/label&gt;<br>                    &lt;input class=&quot;appearance-none block w-full bg-grey-lighter text-grey-darker border rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-grey {{ $errors-&gt;has(&#39;last_name&#39;) ? &#39;border-red mb-3&#39; : &#39;border-grey-lighter&#39; }}&quot; id=&quot;last_name&quot; name=&quot;last_name&quot; type=&quot;text&quot; placeholder=&quot;Doe&quot;&gt;<br>                    @if($errors-&gt;has(&#39;email&#39;))<br>                        &lt;p class=&quot;text-red text-xs italic&quot;&gt;{{ $errors-&gt;first(&#39;last_name&#39;) }}&lt;/p&gt;<br>                    @endif<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;flex flex-wrap -mx-3 mb-6&quot;&gt;<br>                &lt;div class=&quot;w-full px-3&quot;&gt;<br>                    &lt;label class=&quot;block uppercase tracking-wide text-grey-darker text-xs font-bold mb-2&quot; for=&quot;email&quot;&gt;<br>                        Email<br>                    &lt;/label&gt;<br>                    &lt;input class=&quot;appearance-none block w-full bg-grey-lighter text-grey-darker border rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-grey {{ $errors-&gt;has(&#39;email&#39;) ? &#39;border-red mb-3&#39; : &#39;border-grey-lighter&#39; }}&quot; id=&quot;email&quot; name=&quot;email&quot; type=&quot;email&quot; placeholder=&quot;jane@example.com&quot;&gt;<br>                    @if($errors-&gt;has(&#39;email&#39;))<br>                        &lt;p class=&quot;text-red text-xs italic&quot;&gt;{{ $errors-&gt;first(&#39;email&#39;) }}&lt;/p&gt;<br>                    @endif<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;button class=&quot;block bg-blue px-6 py-4 text-white rounded mx-auto hover:bg-blue-dark&quot; type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>        &lt;/form&gt;<br>        @if (session(&#39;form-success&#39;))<br>            &lt;div class=&quot;bg-green mt-8 p-6 rounded shadow&quot;&gt;<br>                &lt;p class=&quot;text-white&quot;&gt;{{ session(&#39;form-success&#39;) }}&lt;/p&gt;<br>            &lt;/div&gt;<br>        @endif<br>    &lt;/div&gt;<br>&lt;/body&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DBWmg9R5rnAuKzp4.png" /></figure><p>Not too shabby! Now, we can hop into our web.php file to define the form-submitroute that our form should POST to.</p><pre>Route::get(&#39;/&#39;, function () {<br>    return view(&#39;welcome&#39;);<br>});</pre><pre>Route::post(&#39;/form-submit&#39;, &#39;LeadController@store&#39;);</pre><p>Inside of our LeadController&#39;s store() method, we&#39;ll do a bit of validation, add some default data using the constants from earlier, and then save a new lead.</p><pre>public function store(Request $request)<br>{<br>    $validatedData = $request-&gt;validate([<br>        &#39;first_name&#39; =&gt; &#39;required|string&#39;,<br>        &#39;last_name&#39; =&gt; &#39;required|string&#39;,<br>        &#39;email&#39; =&gt; &#39;required|email|unique:leads,email&#39;,<br>    ]);</pre><pre>    $lead = new Lead;</pre><pre>    $lead-&gt;first_name = $validatedData[&#39;first_name&#39;];<br>    $lead-&gt;last_name = $validatedData[&#39;last_name&#39;];<br>    $lead-&gt;email = $validatedData[&#39;email&#39;];<br>    $lead-&gt;type = Lead::ORGANIC_TYPE;<br>    $lead-&gt;status = Lead::PROSPECT_STATUS;</pre><pre>    $lead-&gt;save();</pre><pre>    return redirect()-&gt;back()<br>        -&gt;with(&#39;form-success&#39;, &#39;Thank you for your submission!&#39;);<br>}</pre><p>Now our visitors can submit their details. With the Laravel side of things taken care of, we’re ready to move onto Nova!</p><h3>Nova CRM</h3><p>To get our Nova admin panel working, we can start by adding some resources for the Lead and Note models. To do that’ll, we’ll run php artisan nova:resource Leadand php artisan nova:resource:Note from our terminal. With the resources generated, let&#39;s go through the Lead resource from top to bottom and configure it for our app.</p><h3>Resources</h3><p>First up, we have the $model definition which we can leave alone. Next, is the $title - this is what Nova will use to display our Lead around our admin. Let&#39;s update that to our Lead&#39;s full_name so it&#39;s a bit easier to understand at a glance.</p><pre>public static $title = &#39;full_name&#39;;</pre><p>Next, in the $search array, we can define the fields we want to be able to search on. Let&#39;s add a few of our Lead&#39;s attributes so we can find them quickly.</p><pre>public static $search = [<br>    &#39;id&#39;,<br>    &#39;full_name&#39;,<br>    &#39;email&#39;,<br>];</pre><p>With that taken care of, we’re ready to define our fields.</p><pre>public function fields(Request $request)<br>{<br>    return [<br>        ID::make()-&gt;sortable(),<br>        Text::make(&#39;Full Name&#39;)<br>            -&gt;exceptOnForms()<br>            -&gt;sortable(),<br>        Select::make(&#39;Status&#39;)<br>            -&gt;options(\App\Lead::getStatuses())<br>            -&gt;sortable()<br>            -&gt;rules(&#39;required&#39;, &#39;string&#39;),<br>        Select::make(&#39;Type&#39;)<br>            -&gt;options(\App\Lead::getTypes())<br>            -&gt;sortable()<br>            -&gt;rules(&#39;required&#39;, &#39;string&#39;),<br>        Text::make(&#39;First Name&#39;)<br>            -&gt;onlyOnForms()<br>            -&gt;rules(&#39;required&#39;, &#39;string&#39;),<br>        Text::make(&#39;Last Name&#39;)<br>            -&gt;onlyOnForms()<br>            -&gt;rules(&#39;required&#39;, &#39;string&#39;),<br>        Text::make(&#39;Email&#39;)<br>            -&gt;sortable()<br>            -&gt;rules(&#39;required&#39;, &#39;email&#39;)<br>            -&gt;creationRules(&#39;unique:leads,email&#39;)<br>            -&gt;updateRules(&#39;unique:leads,email,{{resourceId}}&#39;),<br>        HasMany::make(&#39;Notes&#39;),<br>    ];<br>}</pre><p>As you can see, we’ve got a lot more going on here than we did in the previous post. For example, we use the exceptOnForms() and onlyOnForms() display options with our name values. On our email field, we&#39;re doing some special validation to ensure that we maintain the uniqueness of the emails.</p><p>Also, notice that our model methods are making an appearance now! We can use them to populate the select fields, so our values keep in sync. Maybe a bit overkill, but I like knowing that I can change that in one place and everything will stay updated. Finally, we can see that all the fields that appear in the index are sortable.</p><p>Taking a look at our Nova admin, we can see that the index has built itself and our forms are now usable!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vHEqu948nlPOd9HQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J8ee0OIRfY21g_BN.png" /></figure><p>Now visitors can submit their data, and our team can upload their leads! It would be nice if we could keep track of any edits or changes that our admin users make on the Leads and Notes for management purposes. Fortunately, Nova makes this super easy!</p><p>We just need to add the Actionable trait to our models, and we&#39;ll get a list of actions performed on the model.</p><pre>//In app\Lead.php and app\Note.php<br>use Actionable;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FEtDgIrDOCm610CE.png" /></figure><p>How cool is that? With our Lead resource set up, let’s work on our Note resource. Now that we’re getting the hang of things let’s quickly run through all of the changes at once.</p><pre>class Note extends Resource<br>{<br>    public static $model = &#39;App\Note&#39;;</pre><pre>    public static $title = &#39;title&#39;;</pre><pre>    public static $search = [<br>        &#39;id&#39;,<br>        &#39;title&#39;,<br>    ];</pre><pre>    public function fields(Request $request)<br>    {<br>        return [<br>            ID::make()-&gt;sortable(),<br>            Text::make(&#39;Title&#39;)<br>                -&gt;sortable()<br>                -&gt;rules(&#39;required&#39;, &#39;string&#39;),<br>            Select::make(&#39;Priority&#39;)<br>                -&gt;options(\App\Note::getPriorities())<br>                -&gt;sortable()<br>                -&gt;rules(&#39;required&#39;, &#39;string&#39;),<br>            Markdown::make(&#39;Body&#39;)<br>                -&gt;rules(&#39;required&#39;, &#39;string&#39;),<br>            BelongsTo::make(&#39;Lead&#39;)<br>                -&gt;sortable()<br>                -&gt;rules(&#39;required&#39;),<br>            BelongsTo::make(&#39;User&#39;)<br>                    -&gt;sortable()<br>                -&gt;rules(&#39;required&#39;),<br>        ];<br>    }<br>    <br>    ...<br>}</pre><p>We haven’t done too much here, apart from the fields() definition, so I&#39;ll let you unpack all of the changes. Finally, we&#39;ll also need to add a relationship definition to our User resource so we can see their Notes.</p><pre>public function fields(Request $request)<br>{<br>    return [<br>        ID::make()-&gt;sortable(),</pre><pre>        Gravatar::make(),</pre><pre>        Text::make(&#39;Name&#39;)<br>            -&gt;sortable()<br>            -&gt;rules(&#39;required&#39;, &#39;max:255&#39;),</pre><pre>        Text::make(&#39;Email&#39;)<br>            -&gt;sortable()<br>            -&gt;rules(&#39;required&#39;, &#39;email&#39;, &#39;max:255&#39;)<br>            -&gt;creationRules(&#39;unique:users,email&#39;)<br>            -&gt;updateRules(&#39;unique:users,email,{{resourceId}}&#39;),</pre><pre>        Password::make(&#39;Password&#39;)<br>            -&gt;onlyOnForms()<br>            -&gt;creationRules(&#39;required&#39;, &#39;string&#39;, &#39;min:6&#39;)<br>            -&gt;updateRules(&#39;nullable&#39;, &#39;string&#39;, &#39;min:6&#39;),</pre><pre>        HasMany::make(&#39;Notes&#39;)<br>    ];<br>}</pre><p>Now we can see the Notes on their index page, their Lead’s page, and their User’s page!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jInfpkV8qWYDJC9B.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sFfKsDXYsAN4vS8W.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CzXrpuQcnV3aksqP.png" /></figure><p>Just like that, we have the CRUD functionality of our CRM all wrapped up. However, we’re missing a few key features that would make our CRM data super actionable. Let’s work on adding those features now!</p><h3>Metrics</h3><p>What’s a CRM without any metrics? Out-of-the-box, Nova makes it super easy for us to add metrics to our admin. So, what do we want to see? It would be great to see the Lead growth over time; how many Leads we’ve gained in a given period, and the breakdown of each type of Lead. Let’s whip those right up!</p><p>Starting with our Lead growth metric, we can use the Nova cli tools to quickly scaffold a trend chart for us by running: php artisan nova:trend LeadsPerDay.</p><p>This command creates a Metrics directory inside of app\Nova. In here, we can see the config for our new trend chart. All we need to do is replace the default Modelvalue with Lead inside the calculate() method.</p><pre>public function calculate(Request $request)<br>{<br>    return $this-&gt;countByDays($request, Lead::class);<br>}</pre><p>Now to display our new trend chart, we’ll pop back into our Lead resource and register it in the cards() method. Since we&#39;d like it to take up half the screen, we&#39;ll also chain on a width(&#39;1/3&#39;) method.</p><pre>public function cards(Request $request)<br>{<br>    return [<br>        (new Metrics\LeadsPerDay)-&gt;width(&#39;1/3&#39;),<br>    ];<br>}</pre><p>If we take a look at our Leads index page, we can see that the chart is ready to go!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rao82IgF3IM-oP53.png" /></figure><p>I don’t know about you, but I’ve spent a significant portion of my life developing custom charts. Nova has made that grueling process a thing of the past. Now, let’s crank out the other two.</p><p>We’ll just run php artisan nova:value NewLeads and php artisan nova:partition LeadsPerStatus. Then, we can hop into those generated files to update the default model with Lead. Inside of LeadsPerStatus, we&#39;ll also use status as the groupByColumn. Then, we&#39;ll register the new metrics like this:</p><pre>public function cards(Request $request)<br>{<br>    return [<br>        (new Metrics\LeadsPerDay)-&gt;width(&#39;1/3&#39;),<br>        (new Metrics\NewLeads)-&gt;width(&#39;1/3&#39;),<br>        (new Metrics\LeadsPerStatus)-&gt;width(&#39;1/3&#39;),<br>    ];<br>}</pre><p>And we’re ready to show off what we “built” at the next stakeholder meeting!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EuRpGwafDCaX0Zeo.png" /></figure><p>I just can’t get over how easy that process has become. It truly is a paradigm shift because now we can focus on features that our users need instead of getting bogged down in the minutiae of bringing data to life. Don’t get me wrong; data wrangling can be fun every now and again. However, building chart after chart can be a little draining. /endrant</p><p>Before we wrap up our CRM, we could use some additional filters and lenses to get a better understanding of our lead data.</p><h3>Filters</h3><p>For example, it would be great if we could filter this list to only look leads according to their type or status. Once again, Nova has an easy way for us to make this happen with filters.</p><p>We can go ahead and use the Nova cli again to generate our filters by running php artisan nova:filter LeadType and php artisan nova:filter LeadStatus. We now have a Filters directory inside of app\Nova where we can config our filters.</p><p>To do that, we’ll add a regular Eloquent query inside of the filter’s apply() method and then list out the options using our convenient model methods.</p><pre>//LeadStatus.php<br>class LeadStatus extends Filter<br>{<br>    public function apply(Request $request, $query, $value)<br>    {<br>        return $query-&gt;where(&#39;status&#39;, $value);<br>    }</pre><pre>    public function options(Request $request)<br>    {<br>        return Lead::getStatuses();<br>    }<br>}</pre><pre>//LeadType.php<br>class LeadType extends Filter<br>{<br>    /**<br>     * Apply the filter to the given query.<br>     *<br>     * @param  \Illuminate\Http\Request  $request<br>     * @param  \Illuminate\Database\Eloquent\Builder  $query<br>     * @param  mixed  $value<br>     * @return \Illuminate\Database\Eloquent\Builder<br>     */<br>    public function apply(Request $request, $query, $value)<br>    {<br>        return $query-&gt;where(&#39;type&#39;, $value);<br>    }</pre><pre>    /**<br>     * Get the filter&#39;s available options.<br>     *<br>     * @param  \Illuminate\Http\Request  $request<br>     * @return array<br>     */<br>    public function options(Request $request)<br>    {<br>        return Lead::getTypes();<br>    }<br>}</pre><p>Now we can register these filters in our Lead resource, and they’ll appear on our index page.</p><pre>public function filters(Request $request)<br>{<br>    return [<br>        new Filters\LeadStatus,<br>        new Filters\LeadType,<br>    ];<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h4QxbFutZqRv8Ttr.png" /></figure><p>There you have it! The crazy thing is that we can even use both filters at the same time to narrow down our dataset even further. I was kind of hoping that our metrics would have updated as well, but hopefully, we’ll see that in a later release!</p><p>Let’s add one more feature to our CRM to bring home the bacon.</p><h3>Lenses</h3><p>In Nova, a lens is similar to a filter except we have full control over how to query and display the data. Having this control is extremely useful — especially if we need to reference a model’s relationships.</p><p>In our case, we’ve noticed that Leads with a high number of Notes tend to cost us money because they’re asking for more customer support. So, it would be great to have a lens so we can have some visibility into this problem.</p><p>Well start this as usual with the Nova cli generator like so: php artisan nova:lens TimeIntensiveLeads. As you may have guessed, this generates a Lenses directory inside of app/Nova where we can see our TimeInstensiveLeads lens.</p><p>Lenses are certainly a step up from filters regarding the work we need to do. We’ll be in charge of writing our query to get the data we need. So. let’s dive in.</p><p>First up, we have the query method where we&#39;ll be defining the query that selects our data.</p><p>Let me preface what you’re about to see by saying that I’m not the world’s best SQL developer, so my apologies if there is a better way to do this. If you do have a better way, feel free to ping me on Twitter, and I’ll get this updated.</p><p>Back to our query, it could look something like this:</p><pre>public static function query(LensRequest $request, $query)<br>{<br>    return $request-&gt;withOrdering($request-&gt;withFilters(<br>        $query-&gt;select([<br>            &#39;leads.id&#39;,<br>            &#39;leads.full_name&#39;,<br>            &#39;leads.email&#39;,<br>            &#39;leads.status&#39;,<br>            &#39;leads.type&#39;,<br>            DB::raw(&#39;count(notes.id) as Count&#39;)<br>        ])<br>        -&gt;join(&#39;notes&#39;, &#39;leads.id&#39;, &#39;=&#39;, &#39;notes.lead_id&#39;)<br>        -&gt;orderBy(&#39;Count&#39;, &#39;desc&#39;)<br>        -&gt;groupBy(&#39;leads.id&#39;, &#39;leads.full_name&#39;)<br>    ));<br>}</pre><p>Now in the fields() method, we can define the how we&#39;ll be displaying this data.</p><pre>public function fields(Request $request)<br>{<br>    return [<br>        ID::make(&#39;ID&#39;, &#39;id&#39;)-&gt;sortable(),<br>        Text::make(&#39;Full Name&#39;)-&gt;sortable(),<br>        Select::make(&#39;Status&#39;)-&gt;sortable(),<br>        Text::make(&#39;Type&#39;)-&gt;sortable(),<br>        Text::make(&#39;Email&#39;)-&gt;sortable(),<br>        Number::make(&#39;Notes Count&#39;, &#39;Count&#39;),<br>    ];<br>}</pre><p>Next, we’ll register our custom filters so we can manipulate the results like we’re used to doing.</p><pre>public function filters(Request $request)<br>{<br>    return [<br>        new LeadStatus,<br>        new LeadType,<br>    ];<br>}</pre><p>Finally, we’ll register this in our Lead resource and check out the results!</p><pre>public function lenses(Request $request)<br>{<br>    return [<br>        new Lenses\TimeIntensiveLeads,<br>    ];<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vL03ppfzkeccqpA3.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t3BJhqWO3tRRDOaw.png" /></figure><p>Just like that, we’ve got ourselves a custom view that provides an actionable look into our data.</p><h3>The Wrap-Up</h3><p>Well, there you have it folks! We’ve used Nova to build a quick CRM for us to use. More importantly, we took a more in-depth look at how we can use Nova’s features to fit our way of developing and use-cases. As you followed along, I hope you had a few eureka moments as you made connections between your problems and the solutions Nova presents.</p><p>I still can’t wait to see what we’ll all be able to build with it! As always, feel free to ask me any questions on <a href="https://twitter.com/nickjbasile">Twitter</a>. And until next time, happy coding!</p><p>To keep learning about Laravel Nova, check out my <a href="https://nick-basile.com/blog/post/improving-our-laravel-nova-crm">next post</a> where I deep dive more features by expanding our CRM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eb413a081ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Laravel Nova]]></title>
            <link>https://nickjbasile.medium.com/getting-started-with-laravel-nova-f2a04fa9df82?source=rss-12d3411267e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2a04fa9df82</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[nova]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[getting-started]]></category>
            <dc:creator><![CDATA[Nick Basile]]></dc:creator>
            <pubDate>Wed, 22 Aug 2018 17:24:06 GMT</pubDate>
            <atom:updated>2018-12-04T15:36:35.321Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Acg9c0ixLMWAowVbNyzP1g.jpeg" /></figure><p>What an exciting day in Laravel history! Today, the latest addition to the Laravel ecosystem has arrived: <a href="https://nova.laravel.com/">Nova</a>. So, what exactly is it?</p><p>Well, straight from the marketing website it’s defined as, “a beautifully designed administration panel for Laravel. Carefully crafted by the creators of Laravel to make you the most productive developer in the galaxy.” In my eyes, it can be everything from an admin panel to a CMS to a CRM, and I’m just scratching the surface. It’s rocket fuel for your Laravel projects that lets you focus on the features that matter to your users.</p><p>I had a chance to grab my license this morning, and I’ve already been blown away by how intuitively Nova fits into my established Laravel workflow. Today, I’ll walk you through how I got started with it by building a quick blog.</p><h3>Getting Started</h3><p>First things first, you’ll need to head over to the Nova website and <a href="https://nova.laravel.com/register">register</a> for an account. Once you’re in, you’ll need to purchase a license to get access to the code.</p><p>The price is $99 for a solo developer and $199 for a team. This may seem steep, but the productivity gains you’ll see should more than make up for the cost. Honestly, I’m already having a hard time envisioning how I would work without it.</p><p>Once you have a license, you can download the Nova files to your machine. Next, create a new laravel project using laravel new &lt;your-project-name&gt; or you can add it to an existing project. From the command line, I used mv &lt;path-to-nova-download&gt; &lt;path-to-my-project-nova-directory&gt; to add it. This way, I was sure to include all of the hidden files like the .gitignore.</p><h3>Project Installation</h3><p>With the source code in place, you can configure your composer.json to recognize Nova by adding this snippet:</p><pre>&quot;repositories&quot;: [<br>    {<br>        &quot;type&quot;: &quot;path&quot;,<br>        &quot;url&quot;: &quot;./nova&quot;<br>    }<br>],</pre><p>Then, you’ll add Nova to the require section of composer.json like this:</p><pre>&quot;require&quot;: {<br>    &quot;php&quot;: &quot;^7.1.3&quot;,<br>    &quot;fideloper/proxy&quot;: &quot;^4.0&quot;,<br>    &quot;laravel/framework&quot;: &quot;5.6.*&quot;,<br>    &quot;laravel/nova&quot;: &quot;*&quot;<br>},</pre><p>Before running the installation commands, make sure you configure your DB in your .env. I was so excited the first time I installed it that I forgot this crucial step and had a fun error to remind me that everyone goofs up every now and again.</p><p>With that setup, you can run the following commands from your terminal to install Nova:</p><pre>composer update</pre><pre>php artisan nova:install</pre><pre>php artisan migrate</pre><p>Bada bing bada boom, Nova is now installed in our project! We can now navigate to the /nova route and see the login screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gn0qO5p4VAduA0Pc.png" /></figure><h3>Add Your First User</h3><p>To log in, we need to create a user. Nova includes an out-of-the-box command so we can register anyone on the fly. We can run php artisan nova:user in our terminal and follow the prompts to add our first user. Now, we&#39;re ready to log in and start our blog!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sEnKh2DlUMlzImu_.png" /></figure><h3>Let’s Build a Blog</h3><p>Let’s start this project like any other Laravel project. We’ll use php artisan make:model Post -a to scaffold our Post model for our blog. Now, we can hop into the migrations and add some columns.</p><pre>public function up()<br>{<br>    Schema::create(&#39;posts&#39;, function (Blueprint $table) {<br>        $table-&gt;increments(&#39;id&#39;);<br>        $table-&gt;integer(&#39;user_id&#39;);<br>        $table-&gt;text(&#39;title&#39;);<br>        $table-&gt;text(&#39;subtitle&#39;);<br>        $table-&gt;text(&#39;body&#39;);<br>        $table-&gt;dateTime(&#39;published_on&#39;);<br>        $table-&gt;timestamps();<br>    });<br>}</pre><p>Now, we can run php artisan migrate to add this table to our database. After that, we can go to our Post.php file and configure the relationships. We also need to make sure we&#39;re casting the dateTime column correctly. I missed that my first time and Nova was smart enough to tell me I messed that up!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S8vabwylrF9h25P-.png" /></figure><p>So our Post.php file will start looking like this:</p><pre>class Post extends Model<br>{<br>    protected $dates = [<br>      &#39;published_on&#39;,<br>    ];</pre><pre>    public function user()<br>    {<br>        return $this-&gt;belongsTo(&#39;App\User&#39;);<br>    }<br>}</pre><p>Now we can define the inverse of the relationship in our User model.</p><pre>class User extends Authenticatable<br>{<br>    use Notifiable;</pre><pre>    /**<br>     * The attributes that are mass assignable.<br>     *<br>     * @var array<br>     */<br>    protected $fillable = [<br>        &#39;name&#39;, &#39;email&#39;, &#39;password&#39;,<br>    ];</pre><pre>    /**<br>     * The attributes that should be hidden for arrays.<br>     *<br>     * @var array<br>     */<br>    protected $hidden = [<br>        &#39;password&#39;, &#39;remember_token&#39;,<br>    ];</pre><pre>    public function posts()<br>    {<br>        return $this-&gt;hasMany(&#39;App\Post&#39;);<br>    }<br>}</pre><p>With our models set up, let’s jump into the Nova side of things!</p><h3>Using Nova</h3><p>In using Nova, we have the concept of <a href="https://nova.laravel.com/docs/1.0/resources/#defining-resources">resources</a>. Every model that you want to manage in Nova has a corresponding resource.</p><p>To generate our Post resource, we can run nova:resource Post. Now, inside of our app\Nova directory, we can see our Post resource! This where we&#39;ll do most of our configuration for how we want Nova to interact with our Post model.</p><p>To start CRUDing Post, we’ll need to configure our fields() method in the Post resource. This is where we tell Nova how to interpret the columns we&#39;ve defined for our model.</p><p>Nova has <a href="https://nova.laravel.com/docs/1.0/resources/fields.html#fields">tons of different</a> fields for us to use, so take a look at the available options when you’re working on your projects. For now, we’ll use some of the basic ones for our Post like this:</p><pre>public function fields(Request $request)<br>{<br>    return [<br>        ID::make()-&gt;sortable(),<br>        BelongsTo::make(&#39;User&#39;)-&gt;rules(&#39;required&#39;),<br>        Text::make(&#39;Title&#39;)-&gt;rules(&#39;required&#39;)-&gt;sortable(),<br>        Text::make(&#39;Subtitle&#39;)-&gt;rules(&#39;required&#39;)-&gt;hideFromIndex(),<br>        Markdown::make(&#39;Body&#39;)-&gt;rules(&#39;required&#39;),<br>        DateTime::make(&#39;Published On&#39;)-&gt;rules(&#39;required&#39;),<br>    ];<br>}</pre><p>Let’s unpack this a bit by looking at the subtitle definition.</p><pre>Text::make(&#39;Subtitle&#39;)-&gt;rules(&#39;required&#39;)-&gt;hideFromIndex(),</pre><p>The Text part tells us what kind of field we&#39;re generating. Then, the label is what we pass to the make() static method. The label is then snake cased to match the underlying column value.</p><p>We’re also adding some extra magic by defining our validation rules with the rules()method. In this case, we&#39;re saying the Subtitle is a required field.</p><p>Finally, we’re tweaking the field’s <a href="https://nova.laravel.com/docs/1.0/resources/fields.html#showing-hiding-fields">display</a> by adding the hideFromIndex() method. This prevents the field from showing up on the list page. Some fields handle this a little differently (i.e. Markdown). However, for the most part, if you don&#39;t specify the display option, then it&#39;ll show up everywhere.</p><p>As easy as that, we’ve built our blog’s entire CMS. If we head back to the dashboard, we can see that a new Posts menu item has appeared under Resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n0oRdY45B-DbTz5g.png" /></figure><p>Clicking on that will take us to the index page for our Posts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xQAL4qax70divhJx.png" /></figure><p>We’re prompted to create a post, and we click the button to get started. This brings up the create form for adding a Post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lg8YSeCr6iEk94oi.png" /></figure><p>If we try to submit the form like this, we can see our validation working as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PNU324qWMAAHGGna.png" /></figure><p>Once we’ve filled out all the details, we’re redirected to the post itself, and we can see all of its info.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vX4FB8bpICzq7uei.png" /></figure><p>Finally, we can head back to the index page and see our newly created Post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZIuvixtlyq75WrB3.png" /></figure><p>Just like that, we’ve built a CMS for a blog. Now, while that takes care of the admin side of things, we still need to make our posts viewable to our users. So, Nova gives us a tremendous head start on our projects, but we’ll still need to earn our developer chops by building the features our users need.</p><h3>Back to Laravel</h3><p>To finish up this blog, we’ll hop into our PostController and set up our user views. For this demo, we only care about index() and show() so we can delete the other methods that were auto-generated for us earlier.</p><p>Now we’ll quickly grab the right data and send our users to some new views.</p><pre>class PostController extends Controller<br>{<br>    public function index()<br>    {<br>        $posts = Post::orderByDesc(&#39;published_on&#39;)-&gt;get();</pre><pre>        return view(&#39;posts&#39;, compact(&#39;posts&#39;));<br>    }</pre><pre>    public function show(Post $post)<br>    {<br>        return view(&#39;post&#39;, compact(&#39;post&#39;));<br>    }<br>}</pre><p>Next, we can update our web.php file by replacing what&#39;s in there with this:</p><pre>Route::get(&#39;/&#39;, &#39;PostController@index&#39;);<br>Route::get(&#39;/posts/{post}&#39;, &#39;PostController@show&#39;);</pre><p>Finally, we’ll rename welcome.php to posts.php. Then we can get rid of the default HTML and use this:</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;{{ app()-&gt;getLocale() }}&quot;&gt;<br>    &lt;head&gt;<br>        &lt;meta charset=&quot;utf-8&quot;&gt;<br>        &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;</pre><pre>        &lt;title&gt;Laravel&lt;/title&gt;</pre><pre>        &lt;!-- Fonts --&gt;<br>        &lt;link href=&quot;https://fonts.googleapis.com/css?family=Nunito:200,600&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;&gt;</pre><pre>        &lt;!-- Styles --&gt;<br>        &lt;style&gt;<br>            html, body {<br>                background-color: #fff;<br>                color: #636b6f;<br>                font-family: &#39;Nunito&#39;, sans-serif;<br>                font-weight: 200;<br>                height: 100vh;<br>                margin: 0;<br>            }</pre><pre>            .m-b-md {<br>                display: block;<br>                margin-bottom: 60px;<br>            }<br>        &lt;/style&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;div&gt;<br>            @foreach($posts as $post)<br>                &lt;a href=&quot;/posts/{{$post-&gt;id}}&quot; class=&quot;m-b-md&quot;&gt;<br>                    &lt;h1&gt;{{$post-&gt;title}}&lt;/h1&gt;<br>                    &lt;h3&gt;{{$post-&gt;subtitle}}&lt;/h3&gt;<br>                    &lt;h4&gt;{{$post-&gt;published_on}}&lt;/h4&gt;<br>                &lt;/a&gt;<br>            @endforeach<br>        &lt;/div&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now we have some blog posts coming through!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nXGJ8cTvzUQJw_HE.png" /></figure><p>Finally, we’ll copy this file and rename it to post.blade.php. Then we can replace it with this:</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;{{ app()-&gt;getLocale() }}&quot;&gt;<br>    &lt;head&gt;<br>        &lt;meta charset=&quot;utf-8&quot;&gt;<br>        &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;</pre><pre>        &lt;title&gt;Laravel&lt;/title&gt;</pre><pre>        &lt;!-- Fonts --&gt;<br>        &lt;link href=&quot;https://fonts.googleapis.com/css?family=Nunito:200,600&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;&gt;</pre><pre>        &lt;!-- Styles --&gt;<br>        &lt;style&gt;<br>            html, body {<br>                background-color: #fff;<br>                color: #636b6f;<br>                font-family: &#39;Nunito&#39;, sans-serif;<br>                font-weight: 200;<br>                height: 100vh;<br>                margin: 0;<br>            }<br>        &lt;/style&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;div&gt;<br>            &lt;h1&gt;{{$post-&gt;title}}&lt;/h1&gt;<br>            &lt;h3&gt;{{$post-&gt;subtitle}}&lt;/h3&gt;<br>            &lt;h4&gt;Written by {{$post-&gt;user-&gt;name}} on {{$post-&gt;published_on}}&lt;/h4&gt;<br>        &lt;/div&gt;<br>        &lt;article&gt;{{$post-&gt;body}}&lt;/article&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Taking a look, we can see our blog post!</p><h3>The Wrap-Up</h3><p>I don’t know about you, but that is the fastest amount of time I’ve ever built a blog in. Nova is a real game-changer, and we barely scratched the surface in terms of what it’s capable of doing. Plus, with all of the <a href="https://novapackages.com/">incredible packages</a> that folks are already releasing, we’re in for some great times ahead.</p><p>I think we all owe the Laravel team a big round of applause for this incredibly well thought-out and executed tool. I can’t wait to see what we’ll all be able to build with it! As always, feel free to ask me any questions on <a href="https://twitter.com/nickjbasile">Twitter</a>. And until next time, happy coding!</p><p>To keep learning about Laravel Nova, check out my <a href="https://nick-basile.com/blog/post/deep-diving-laravel-nova">next post</a> where I deep dive more features by building a simple CRM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2a04fa9df82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building A Comments System With Vue.js, Laravel, and Tailwind CSS Part III]]></title>
            <link>https://nickjbasile.medium.com/building-a-comments-system-with-vue-js-laravel-and-tailwind-css-part-iii-84f35cf8ff9b?source=rss-12d3411267e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/84f35cf8ff9b</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Nick Basile]]></dc:creator>
            <pubDate>Thu, 03 May 2018 14:54:00 GMT</pubDate>
            <atom:updated>2018-12-04T15:36:22.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTbwQjdOkgJ-4KpyyPGCkA.jpeg" /></figure><p>Now that we have our comments <a href="https://nick-basile.com/blog/post/building-a-comments-system-with-vuejs-laravel-and-tailwind-css-part-i">functionality</a> in place with Vue.js and our components <a href="https://nick-basile.com/blog/post/building-a-comments-system-with-vuejs-laravel-and-tailwind-css-part-ii">styled</a> by Tailwind CSS, it’s time to start using Laravel to persist our comments.</p><h3>The Set Up</h3><p>Let’s get this show on the road by setting up our Comment model. We’ll run php artisan make:model Comment -a to set up the model and all of the other files that we need to manage our comments.</p><p>As we can see, this command will create a migration, factory, controller, and model for us. Now, that we have our files let’s start working on our migration.</p><h3>The Migration</h3><p>Looking in our database/migrations directory, we can see that we&#39;ve added a migration to create a comments_table. With our migration, we&#39;ll be able to define the database schema for our comments.</p><p>Opening up our file, we can see that Laravel has provided us with some boilerplate out of the box. We’ll need to add a field for the user_id so we can keep track of who wrote a comment and a body field for the comment itself.</p><pre>public function up()<br>{<br>    Schema::create(&#39;comments&#39;, function (Blueprint $table) {<br>        $table-&gt;increments(&#39;id&#39;);<br>        $table-&gt;integer(&#39;user_id&#39;);<br>        $table-&gt;longText(&#39;body&#39;);<br>        $table-&gt;timestamps();<br>    });<br>}</pre><p>Just like that, we have our schema defined! Now we can hop to the command line and run php artisan migrate to add that table to our database.</p><p>With our database taken care of, let’s focus on our factory so we can create some dummy data.</p><h3>The Factory</h3><p>Factories let us quickly spin up “dummy” data that we can use with our applications in development. They’re incredibly useful if you wanted to write tests for our code — but that’s a blog post for another day.</p><p>Let’s open up database/factories/CommentFactory.php. Once again, Laravel has provided us with some boilerplate to get us started. Since our comments have a relationship with a user, we&#39;ll need to create a User to define the user_id. Then we can use the built-in Faker library to generate some dummy text for the body.</p><pre>&lt;?php</pre><pre>use Faker\Generator as Faker;</pre><pre>$factory-&gt;define(App\Comment::class, function (Faker $faker) {<br>    $user = factory(App\User::Class)-&gt;create();</pre><pre>    return [<br>        &#39;user_id&#39; =&gt; $user-&gt;id,<br>        &#39;body&#39; =&gt; $faker-&gt;sentence,<br>    ];<br>});</pre><p>We’re cooking with gas today! If we head to our command line, we can run php artisan tinker to test out our new factory. Inside of tinker, we can write PHP or Laravel code and then execute it in the context of our project. This is such an awesome feature for rapidly testing new features or ideas.</p><p>We’ll go ahead and run factory(\App\Comment::class, 5)-&gt;create(); to add 5 comments to our database. Now if we query for the comments with Eloquent, we can see all of the comments we just created.</p><pre>&gt;&gt;&gt; \App\Comment::all();<br>=&gt; Illuminate\Database\Eloquent\Collection {#808<br>     all: [<br>       App\Comment {#812<br>         id: 1,<br>         user_id: 1,<br>         body: &quot;Iure ratione laborum provident necessitatibus dolore.&quot;,<br>         created_at: &quot;2018-05-02 23:08:37&quot;,<br>         updated_at: &quot;2018-05-02 23:08:37&quot;,<br>       },<br>       App\Comment {#813<br>         id: 2,<br>         user_id: 2,<br>         body: &quot;Sed mollitia dolorum itaque reprehenderit tempora.&quot;,<br>         created_at: &quot;2018-05-02 23:08:37&quot;,<br>         updated_at: &quot;2018-05-02 23:08:37&quot;,<br>       },<br>       App\Comment {#814<br>         id: 3,<br>         user_id: 3,<br>         body: &quot;Tenetur a et consequatur expedita eligendi voluptatem atque.&quot;,<br>         created_at: &quot;2018-05-02 23:08:37&quot;,<br>         updated_at: &quot;2018-05-02 23:08:37&quot;,<br>       },<br>       App\Comment {#815<br>         id: 4,<br>         user_id: 4,<br>         body: &quot;Cum id perferendis corrupti et qui.&quot;,<br>         created_at: &quot;2018-05-02 23:08:37&quot;,<br>         updated_at: &quot;2018-05-02 23:08:37&quot;,<br>       },<br>       App\Comment {#816<br>         id: 5,<br>         user_id: 5,<br>         body: &quot;Doloremque et a adipisci non officia.&quot;,<br>         created_at: &quot;2018-05-02 23:08:37&quot;,<br>         updated_at: &quot;2018-05-02 23:08:37&quot;,<br>       },<br>     ],<br>   }</pre><p>Your comments might look a little different than mine, but we’ve got them in the database! Now let’s head over to our model file and set that up.</p><h3>The Model</h3><p>Inside of our app directory, we&#39;ll find our Comment.php file. This is where we can define our relationships and what data we should be exposing in our queries.</p><p>This is critically important from a security standpoint, so we’ll want to make sure we handle it correctly. We’ll add a protected variable called $fillable where we can define the fields that we&#39;d like to make editable to safeguard against a <a href="https://laravel.com/docs/5.6/eloquent#mass-assignment">mass-assignment vulnerability</a>.</p><pre>protected $fillable = [<br>    &#39;body&#39;,<br>    &#39;user_id&#39;,<br>];</pre><p>Next up, we can add a protected $casts variable to set make sure our user_idalways comes through as an integer.</p><pre>protected $casts = [<br>    &#39;user_id&#39; =&gt; &#39;integer&#39;,<br>];</pre><p>This isn’t strictly required, but I find it helps me quickly scan a model to and remind myself about some of the data types we’re using.</p><p>Finally, we’ll need to define our author relationship. As you may recall, as we were scaffolding our comments in our Vue components, we called the user who created the comment the author. So, to maintain that structure, we&#39;ll need to define our relationship a bit differently than usual.</p><pre>public function author()<br>{<br>    return $this-&gt;belongsTo(User::class, &#39;user_id&#39;);<br>}</pre><p>The name of the method takes care of name for use, but we need to reference the User::class and explicitly define the user_id as the foreign key so Laravel can figure out how to map the way the data is structured to our naming convention.</p><p>With our Comment model set up, we can jump into User.php and add the inverse of our author relationship to our user.</p><pre>public function comments()<br>{<br>    return $this-&gt;hasMany(Comment::class);<br>}</pre><p>With our models set up, we’re ready to figure out our controller.</p><h3>The Controller</h3><p>We’ll find our CommentController.php inside of app/Http/Controllers. Once again, Laravel has provided us with some useful boilerplate. But, we won&#39;t need all of these methods so we can go ahead and delete create(), edit(), and `show().</p><p>With our controller all cleaned up, let’s start with index(). Following our &quot;REST-ful&quot; pattern, the index() method will fetch all of our comments for us. We&#39;ll also want to make sure to eager load our author relationship.</p><pre>public function index()<br>{<br>    $comments = Comment::with(&#39;author&#39;)<br>        -&gt;orderByDesc(&#39;id&#39;)<br>        -&gt;get();</pre><pre>    return response($comments, 200);<br>}</pre><p>Nice! Now we can wire up our store() method. We&#39;ll use this to add new comments to our application. First, we&#39;ll validate that the incoming data contains a body.</p><p>Then, we’ll use the authenticated user’s comments relationship to create the new comment. With this approach, we don’t have to worry about manually setting the user_id because Laravel will take care of that for us!</p><p>Finally, once our comment is created, we’ll make sure to load() the author relationship because we&#39;re expecting that data in our Vue component.</p><pre>public function store(Request $request)<br>{<br>    $data = $request-&gt;validate([<br>        &#39;body&#39; =&gt; &#39;required|string&#39;<br>    ]);</pre><pre>    $comment = auth()-&gt;user()<br>        -&gt;comments()<br>        -&gt;create($data);</pre><pre>    $comment-&gt;load(&#39;author&#39;);</pre><pre>    return response($comment, 200);<br>}</pre><p>We’re flying now! Now that we can create new comments let’s work on updating existing ones. For that, we can move to the aptly named update() method.</p><p>For the update() method, we&#39;ll get a little fancy and use route-model binding to &quot;automatically&quot; retrieve the comment we&#39;d like to edit. Once again, we&#39;ll validate that the incoming data has a body for us to update.</p><p>If that checks out, we’ll update our comment and load() our author relationship again.</p><pre>public function update(Request $request, Comment $comment)<br>{<br>    $data = $request-&gt;validate([<br>        &#39;body&#39; =&gt; &#39;required|string&#39;<br>    ]);</pre><pre>    $comment-&gt;body = $data[&#39;body&#39;];</pre><pre>    $comment-&gt;save();</pre><pre>    $comment-&gt;load(&#39;author&#39;);</pre><pre>    return response($comment, 200);<br>}</pre><p>We’re down to our last controller method: destroy(). We&#39;ll leverage route-model binding once again to retrieve the comment that needs to be deleted, and then we&#39;ll delete it.</p><pre>public function destroy(Comment $comment)<br>{<br>    $comment-&gt;delete();</pre><pre>    return response( null,204);<br>}</pre><p>With our controller functionality all wrapped up, we’ll need to add some routes so our Vue components can use it.</p><h3>Routing</h3><p>Since this functionality lives in the same app, we can define our routes in the usual web.php file. We&#39;ll need to define a route for each of the controller methods we created. And, if the method uses route-model binding, we&#39;ll need to define our comment in the route.</p><pre>Route::get(&#39;/comments&#39;, &#39;CommentController@index&#39;);<br>Route::post(&#39;/comments&#39;, &#39;CommentController@store&#39;);<br>Route::put(&#39;/comments/{comment}&#39;, &#39;CommentController@update&#39;);<br>Route::delete(&#39;/comments/{comment}&#39;, &#39;CommentController@destroy&#39;);</pre><p>We continued our “REST-ful” pattern and used the HTTP request that corresponded to our controller method. With our routes defined, it’s time for us to update our Vue components to interact with our backend data.</p><h3>Sharing The Data With Vue</h3><p>Hopping into CommentsManager.vue, let&#39;s start by fetching our dummy comments from the database. We&#39;ll go ahead and add a fetchComments() method to our component. In the method, we&#39;ll make an AJAX request using Axios and then set our comments data to the response returned from the request.</p><pre>fetchComments() {<br>    const t = this;</pre><pre>    axios.get(&#39;/comments&#39;)<br>        .then(({data}) =&gt; {<br>            t.comments = data;<br>        })<br>},</pre><p>Awesome! Now we need to fire this method when our component is created. So, we’ll hook into Vue’s created lifecycle method and call our new method then.</p><pre>created() {<br>    this.fetchComments();<br>},</pre><p>If we give our page a refresh, we can see that our comments are being pulled from the database! Now we can clear out the hard-coded comments that we used to build out our Vue component because we don’t need them anymore.</p><pre>data: function() {<br>    return {<br>        state: &#39;default&#39;,<br>        data: {<br>            body: &#39;&#39;<br>        },<br>        comments: []<br>    }<br>},</pre><p>Let’s work on adding new comments now. Currently, we’re using the saveComment()method to add new comments locally. But, we want to make sure that they&#39;re getting saved in the database.</p><p>Once again we’ll use Axios to make our POST request. Then we’ll add our new comment to the beginning of our comments Array and toggle the editing state.</p><pre>saveComment() {<br>    const t = this;</pre><pre>    axios.post(&#39;/comments&#39;, t.data)<br>        .then(({data}) =&gt; {<br>            t.comments.unshift(data);</pre><pre>            t.stopEditing();<br>        })<br>},</pre><p>Now we’re ready to work on the updateComment() and deleteComment()methods. I noticed that we had some duplicate functionality for finding the index of our comments, so I extracted that to its own method.</p><pre>commentIndex(commentId) {<br>    return this.comments.findIndex((element) =&gt; {<br>        return element.id === commentId;<br>    });<br>}</pre><p>For our updateComment() method, we&#39;ll make a PUT request using the comment.id we received from our $event. Then we can use the response data to update our existing comment&#39;s body.</p><pre>updateComment($event) {<br>    const t = this;</pre><pre>    axios.put(`/comments/${$event.id}`, $event)<br>        .then(({data}) =&gt; {<br>            t.comments[t.commentIndex($event.id)].body = data.body;<br>        })<br>},</pre><p>Finally, we can do a similar refactor to our deleteComment() method, but instead of updating the body we can .splice() it from the comments Array.</p><pre>deleteComment($event) {<br>    const t = this;</pre><pre>    axios.delete(`/comments/${$event.id}`, $event)<br>        .then(() =&gt; {<br>            t.comments.splice(t.commentIndex($event.id), 1);<br>        })<br>},</pre><p>Just like that our frontend is wired up and talking to our backend!</p><h3>The Wrap-Up</h3><p>We’ve certainly covered a lot of ground in this series. We started with a Vue component, styled it up with Tailwind, and now we’re persisting our comments with Laravel. Pretty impressive work!</p><p>While we have the core functionality down, there’s always room for improvement. We could add some loading indicators during our AJAX calls; implement error handling for when things go wrong, or write some tests so we can have the confidence we need to make changes.</p><p>What do you think we could improve? I’d love to hear/see what you come up with! As always, feel free to ask me any questions on <a href="https://twitter.com/nickjbasile">Twitter</a>. And until next time, happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84f35cf8ff9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building A Comments System With Vue.js, Laravel, and Tailwind CSS Part II]]></title>
            <link>https://nickjbasile.medium.com/building-a-comments-system-with-vue-js-laravel-and-tailwind-css-part-ii-2d682efb0a31?source=rss-12d3411267e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d682efb0a31</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Nick Basile]]></dc:creator>
            <pubDate>Thu, 26 Apr 2018 00:27:23 GMT</pubDate>
            <atom:updated>2018-12-04T15:36:05.552Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I4kNKF1MI99L2iMqq0it-g.jpeg" /></figure><p>Last week, <a href="https://nick-basile.com/blog/post/building-a-comments-system-with-vuejs-laravel-and-tailwind-css-part-i">we started</a> building our comments system with some Vue.js components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W2l2i7QkkwvmGDTY.png" /></figure><p>Now that we have our functionality in place let’s style everything with Tailwind CSS. If you’d like to follow along, feel free to check out <a href="https://github.com/nickbasile/comments-demo/tree/article-2">the repository</a> on GitHub.</p><h3>Where To Start?</h3><p>When we’re styling a new component or page, we typically have two obvious places to start. We can style all of the little page elements atomically, or we can start with the big picture and get the page layout done.</p><p>I find that I’ll take the atomic approach on an established project where I have a better sense of what each element should look like, and because my layout is usually fixed by then. On a more greenfield project like this one, I find myself drawn to creating the layout first because I find that having a layout helps me design a better visual hierarchy for the page elements.</p><p>In your projects, it’s always a great idea to make a note of your development patterns and style. There’s no right or wrong approach, just your way of doing things. So, developing an understanding of your behavior helps you be consistent in your approach while also highlighting areas that could use improvement or experimentation.</p><p>For this project, let’s start with our page layout and work from there.</p><h3>Laying Out The Page</h3><p>Since we’re working from the outside in, we can start all the way at the beginning with our &lt;body&gt; tag inside of app.blade.php. Now, we shouldn&#39;t necessarily use the &lt;body&gt; for helping with the layout. Because, when we use a template system like blade or Vue and then use the &lt;body&gt; for layout, we can find ourselves designed into corners where different templates break the initial layout.</p><p>Next thing you know, we have a couple of different top-level layout templates, and our project is much harder to maintain. That said, we can use the &lt;body&gt; for styles that we&#39;ll use throughout our project. For us, that means we can add the font family here, and we&#39;ll also apply a slightly off-white background color.</p><p>Whenever we’re looking to level up a design, picking a high-quality font is a great place to start. For this project, let’s use the <a href="https://fonts.google.com/specimen/Nunito">Nunito</a> font. To add it to our project, we’ll import it at the top of our app.sass file, and we&#39;ll modify our Tailwind config to add a class for it.</p><pre>//app.sass<br>@import url(https://medium.com/&#39;https://fonts.googleapis.com/css?family=Nunito:300,400,400i,700&#39;)</pre><pre>//tailwind.js<br>fonts: {<br>    ...<br>    &#39;nunito&#39;: [<br>        &#39;Nunito&#39;,<br>        &#39;sans-serif&#39;,<br>    ]<br>},</pre><p>If we run npm run watch, we&#39;ll compile our new class into our stylesheet and watch for any other changes we make.</p><p>Heading back to app.blade.php, we can add .bg-grey-lightest and .font-nunito to our &lt;body&gt;.</p><pre>//app.blade.php<br>&lt;body class=&quot;bg-grey-lightest font-nunito&quot;&gt;<br>    ...<br>&lt;/body&gt;</pre><p>Looking at our browser now, we can see that our page is already starting to come together!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wHIf2KQMK5RW_onP.png" /></figure><p>Adding a simple, off-white background color adds a bit of contrast to the page and helps the nav and content stand out. And our Nunito font makes the typography rounder, smoother, and a bit friendlier.</p><p>Now we can move onto our &lt;nav&gt;. Out-of-the-box, Laravel hooks us up with the latest version of Bootstrap and provides some default styling. For the most part, it&#39;s pretty good. We&#39;ll make a few tweaks to make it line up better with our comments.</p><p>On the &lt;nav&gt;, we can add .px-5 to add some whitespace around the edges. Then, inside of the &lt;nav&gt; we can see a &lt;div&gt; with a class of .container. On this &lt;div&gt; we&#39;ll add .max-w-3xl and .p-0 to override the .container&#39;s styles.</p><pre>//app.blade.php<br>&lt;nav class=&quot;navbar navbar-expand-md navbar-light navbar-laravel px-5&quot;&gt;<br>    &lt;div class=&quot;container max-w-3xl p-0&quot;&gt;<br>        ...<br>    &lt;/div&gt;<br>&lt;/nav&gt;</pre><p>This is an excellent example of how we can use Tailwind in conjunction with Bootstrap to get the customization our project needs. Before we hop into our Vue files, we have one more class left in app.blade.php.</p><blockquote><em>Pro Tip: If you’re going to be mixing Bootstrap and Tailwind extensively, make sure you enable the Tailwind prefix because they share a few class names.</em></blockquote><p>On the &lt;main&gt; tag, we&#39;ll add .px-5 to give our content the same padding as our &lt;nav&gt;.</p><pre>//app.blade.php<br>&lt;main class=&quot;py-4 px-5&quot;&gt;<br>    @yield(&#39;content&#39;)<br>&lt;/main&gt;</pre><p>Just like that, we have the bulk of our layout taken care of, and we didn’t have to write any CSS to customize Bootstrap!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*svs7-eoM1-IQUazX.png" /></figure><h3>Styling The Add Comment Form</h3><p>With our layout mostly taken care of, let’s move onto styling our comments. We can start by styling our “Add Comment” form, but before that, we have one more layout style to finish.</p><p>Hoping into CommentsManager.vue, we can add .max-w-3xl and .mx-auto to the outermost &lt;div&gt; so it stays centered on our page.</p><pre>//CommentsManager.vue<br>&lt;template&gt;<br>    &lt;div class=&quot;max-w-3xl mx-auto&quot;&gt;<br>        ...<br>    &lt;/div&gt;<br>&lt;/template&gt;</pre><p>Inside of our wrapper &lt;div&gt;, we have two other &lt;div&gt;s. We&#39;ll focus on the first one for now. Let&#39;s start by adding a few classes to that &lt;div&gt; to make it look like a distinct entity on the page.</p><pre>//CommentsManager.vue<br>&lt;template&gt;<br>    &lt;div class=&quot;max-w-3xl mx-auto&quot;&gt;<br>        &lt;div class=&quot;bg-white rounded shadow-sm p-8 mb-4&quot;&gt;<br>            ...<br>        &lt;/div&gt;<br>        ...<br>    &lt;/div&gt;<br>&lt;/template&gt;</pre><p>Inside of here, we have the header section enclosed in a &lt;div&gt;. Let&#39;s give that some vertical spacing and make the &lt;h2&gt;&#39;s color a little less intense.</p><pre>//CommentsManager.vue<br>&lt;div class=&quot;bg-white rounded shadow-sm p-8 mb-4&quot;&gt;<br>    &lt;div class=&quot;mb-4&quot;&gt;<br>        &lt;h2 class=&quot;text-black&quot;&gt;Comments&lt;/h2&gt;<br>    &lt;/div&gt;<br>    ...<br>&lt;/div&gt;</pre><p>Lately, I’ve been enjoying using <a href="https://twitter.com/steveschoger">Steve Schoger</a>’s approach to form inputs where he makes them grey instead of messing with the border colors. This does an excellent job of making the inputs easier to read and more distinct on the page. So, let’s take that approach with our &lt;textarea&gt;.</p><pre>//CommentsManager.vue<br>&lt;div class=&quot;bg-white rounded shadow-sm p-8 mb-4&quot;&gt;<br>    &lt;div class=&quot;mb-4&quot;&gt;<br>        &lt;h2 class=&quot;text-black&quot;&gt;Comments&lt;/h2&gt;<br>    &lt;/div&gt;<br>    &lt;textarea v-model=&quot;data.body&quot;<br>              placeholder=&quot;Add a comment&quot;<br>              class=&quot;bg-grey-lighter rounded leading-normal resize-none w-full h-10 py-2 px-3&quot;&gt;<br>    &lt;/textarea&gt;<br>    ...<br>&lt;/div&gt;</pre><p>Finally, we’re ready for our &lt;buttons&gt;! Let&#39;s make the primary action distinct and the secondary one a bit more subtle.</p><pre>//CommentsManager.vue<br>&lt;div class=&quot;bg-white rounded shadow-sm p-8 mb-4&quot;&gt;<br>    &lt;div class=&quot;mb-4&quot;&gt;<br>        &lt;h2 class=&quot;text-black&quot;&gt;Comments&lt;/h2&gt;<br>    &lt;/div&gt;<br>    &lt;textarea v-model=&quot;data.body&quot;<br>              placeholder=&quot;Add a comment&quot;<br>              class=&quot;bg-grey-lighter rounded leading-normal resize-none w-full h-10 py-2 px-3&quot;&gt;<br>    &lt;/textarea&gt;<br>    &lt;div class=&quot;mt-3&quot;&gt;<br>        &lt;button class=&quot;border border-blue bg-blue text-white hover:bg-blue-dark py-2 px-4 rounded tracking-wide mr-1&quot; @click=&quot;saveComment&quot;&gt;Save&lt;/button&gt;<br>        &lt;button class=&quot;border border-grey-darker text-grey-darker hover:bg-grey-dark hover:text-white py-2 px-4 rounded tracking-wide ml-1&quot;&gt;Cancel&lt;/button&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Let’s take a peek at our browser and see what we’re working with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/0*3DnPDMo--dIr1HPb.png" /></figure><p>Mamma mia, that is a beautiful looking form. Now at this point, I hope you have one big question for me, “What the heck is that Cancel button there for?” Let’s take care of that right now.</p><h3>Wiring Up The Cancel Button</h3><p>Vue.js sneaking into the Tailwind section of this series, what blasphemy! I left it to this point because we’ll use it to make a UI upgrade instead of for a core piece of functionality. We’re going to be leveraging Vue’s dynamic classes to expand the &lt;textarea&gt; when the user is ready to add a comment and then the cancel button to exit that state.</p><p>Let’s start off by adding a state property to our data.</p><pre>//CommentsManager.vue<br>data: function() {<br>    return {<br>         state: &#39;default&#39;,<br>        data: {<br>            body: &#39;&#39;<br>        },<br>        comments: [<br>            {<br>                id: 1,<br>                body: &quot;How&#39;s it going?&quot;,<br>                edited: false,<br>                created_at: new Date().toLocaleString(),<br>                author: {<br>                    id: 1,<br>                    name: &#39;Nick Basile&#39;,<br>                }<br>            },<br>            {<br>                id: 2,<br>                body: &quot;Pretty good. Just making a painting.&quot;,<br>                edited: false,<br>                created_at: new Date().toLocaleString(),<br>                author: {<br>                    id: 2,<br>                    name: &#39;Bob Ross&#39;,<br>                }<br>            }<br>        ]<br>    }<br>},</pre><p>Now we can add some methods to toggle the edit state. We can also update our saveComment() method to use our new methods.</p><pre>//CommentsManager.vue<br>methods: {<br>    startEditing() {<br>        this.state = &#39;editing&#39;;<br>    },<br>    stopEditing() {<br>        this.state = &#39;default&#39;;<br>        this.data.body = &#39;&#39;;<br>    },<br>    ...<br>    saveComment() {<br>        let newComment = {<br>            id: this.comments[this.comments.length - 1].id + 1,<br>            body: this.data.body,<br>            edited: false,<br>            created_at: new Date().toLocaleString(),<br>            author: {<br>                id: this.user.id,<br>                name: this.user.name,<br>            }<br>        }<br>    <br>        this.comments.push(newComment);<br>    <br>        this.stopEditing();<br>    }<br>}</pre><p>With those methods in place, we can start wiring up our template! We’ll start by adding that dynamic class to our &lt;textarea&gt; to toggle the height of the element when we&#39;re editing. We&#39;ll also bind startEditing to the @focus event so we can update the state when the user starts writing.</p><p>We’ll add a v-show to our &lt;button&gt;s wrapper &lt;div&gt; to hide them when we&#39;re not editing, and we&#39;ll wire up that mysterious Cancel button, so it starts working.</p><pre>//CommentsManager.vue<br>&lt;textarea v-model=&quot;data.body&quot;<br>          placeholder=&quot;Add a comment&quot;<br>          class=&quot;bg-grey-lighter rounded leading-normal resize-none w-full py-2 px-3&quot;<br>          :class=&quot;[state === &#39;editing&#39; ? &#39;h-24&#39; : &#39;h-10&#39;]&quot;<br>          @focus=&quot;startEditing&quot;&gt;<br>&lt;/textarea&gt;<br>&lt;div v-show=&quot;state === &#39;editing&#39;&quot; class=&quot;mt-3&quot;&gt;<br>    &lt;button class=&quot;border border-blue bg-blue text-white hover:bg-blue-dark py-2 px-4 rounded tracking-wide mr-1&quot; @click=&quot;saveComment&quot;&gt;Save&lt;/button&gt;<br>    &lt;button class=&quot;border border-grey-darker text-grey-darker hover:bg-grey-dark hover:text-white py-2 px-4 rounded tracking-wide ml-1&quot; @click=&quot;stopEditing&quot;&gt;Cancel&lt;/button&gt;<br>&lt;/div&gt;</pre><p>Hopping back into our browser, we can see that the buttons are now hidden until we focus on our &lt;textarea&gt;. I think this is a nice UI pattern because it doesn&#39;t clutter the interface with too much information, but it still provides that additional detail when the context needs it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*i7hFcOi4GgFlFUNK.png" /></figure><p>Now, let’s finish styling the rest of our comments.</p><h3>Styling The Comments</h3><p>Once again, we’ll start from the outside in. Inside of CommentsManager.vue, we have a &lt;div&gt; wrapping our CommentItems. We&#39;ll start by adding the background classes that we used on the &quot;Add Comment&quot; form to this. We&#39;ll also start tracking the index in the v-for and use another dynamic class to apply some margin-bottom to every CommentItem except the last one.</p><pre>//CommentsManager.vue<br>&lt;div class=&quot;bg-white rounded shadow-sm p-8&quot;&gt;<br>    &lt;comment v-for=&quot;(comment, index) in comments&quot;<br>             :key=&quot;comment.id&quot;<br>             :user=&quot;user&quot;<br>             :comment=&quot;comment&quot;<br>             :class=&quot;[index === comments.length - 1 ? &#39;&#39; : &#39;mb-6&#39;]&quot;<br>             @comment-updated=&quot;updateComment($event)&quot;<br>             @comment-deleted=&quot;deleteComment($event)&quot;&gt;<br>    &lt;/comment&gt;<br>&lt;/div&gt;</pre><p>With the wrapper &lt;div&gt; taken care of, we can hop into CommentItem.vue to take care of the comment styles. We&#39;ll start with the comment itself. We can add some positioning classes to its wrapper &lt;div&gt;, then we&#39;ll style the text itself, and finally we can add some styling to the Edit button as well.</p><pre>//CommentItem.vue<br>&lt;div class=&quot;flex justify-between mb-1&quot;&gt;<br>    &lt;p class=&quot;text-grey-darkest leading-normal text-lg&quot;&gt;{{comment.body}}&lt;/p&gt;<br>    &lt;button v-if=&quot;editable&quot; @click=&quot;state = &#39;editing&#39;&quot; class=&quot;ml-2 mt-1 mb-auto text-blue hover:text-blue-dark text-sm&quot;&gt;Edit&lt;/button&gt;<br>&lt;/div&gt;</pre><p>Moving right along, we can style the meta info next. We’ll add some text styling and make sure the bullet span is a little smaller and spaced nicely.</p><pre>//CommentItem.vue<br>&lt;div class=&quot;text-grey-dark leading-normal text-sm&quot;&gt;<br>    &lt;p&gt;{{comment.author.name}} &lt;span class=&quot;mx-1 text-xs&quot;&gt;&amp;bull;&lt;/span&gt; {{ comment.created_at}}&lt;/p&gt;<br>&lt;/div&gt;</pre><p>Heading back to our browser, we can see that our comments have come to life!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/0*irkaDIcCPTLLZ1IV.png" /></figure><p>All we have to do now is style the update form. This will be pretty similar to our “Add Comment” form, but we’ll make sure to give the &lt;textarea&gt; a non-dynamic height and style the delete button a bit differently than the other buttons.</p><pre>//CommentItem.vue<br>&lt;div v-show=&quot;state === &#39;editing&#39;&quot;&gt;<br>    &lt;div class=&quot;mb-3&quot;&gt;<br>        &lt;h3 class=&quot;text-black text-xl&quot;&gt;Update Comment&lt;/h3&gt;<br>    &lt;/div&gt;<br>    &lt;textarea v-model=&quot;data.body&quot;<br>              placeholder=&quot;Update comment&quot;<br>              class=&quot;bg-grey-lighter rounded leading-normal resize-none w-full h-24 py-2 px-3&quot;&gt;<br>    &lt;/textarea&gt;<br>    &lt;div class=&quot;flex flex-col md:flex-row items-center mt-2&quot;&gt;<br>        &lt;button class=&quot;border border-blue bg-blue text-white hover:bg-blue-dark py-2 px-4 rounded tracking-wide mb-2 md:mb-0 md:mr-1&quot; @click=&quot;saveEdit&quot;&gt;Update&lt;/button&gt;<br>        &lt;button class=&quot;border border-grey-darker text-grey-darker hover:bg-grey-dark hover:text-white py-2 px-4 rounded tracking-wide mb-2 md:mb-0 md:ml-1&quot; @click=&quot;resetEdit&quot;&gt;Cancel&lt;/button&gt;<br>        &lt;button class=&quot;text-red hover:bg-red hover:text-white py-2 px-4 rounded tracking-wide mb-2 md:mb-0 md:ml-auto&quot; @click=&quot;deleteComment&quot;&gt;Delete&lt;/button&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/0*U5FjY4Qxh96WMhaP.png" /></figure><p>Bada bing bada boom, we have ourselves some styled comments.</p><h3>The Wrap-Up</h3><p>Every time I get to make a UI from scratch with Tailwind, I’m always blown away by how fast and straightforward it is. We didn’t write any custom CSS, we worked with another framework, and we have some awesome looking comments.</p><p>Now that our styling is done, in the <a href="https://medium.com/@nickjbasile/building-a-comments-system-with-vue-js-laravel-and-tailwind-css-part-iii-84f35cf8ff9b">next post</a>, we can work on using Laravel and MySQL to persist our comments. As always, feel free to ask me any questions on <a href="https://twitter.com/nickjbasile">Twitter</a>. And until next time, happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d682efb0a31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building A Comments System With Vue.js, Laravel, and Tailwind CSS Part I]]></title>
            <link>https://nickjbasile.medium.com/building-a-comments-system-with-vue-js-laravel-and-tailwind-css-part-i-e24e8518ee3?source=rss-12d3411267e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e24e8518ee3</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Nick Basile]]></dc:creator>
            <pubDate>Wed, 18 Apr 2018 23:01:31 GMT</pubDate>
            <atom:updated>2020-12-17T18:57:47.471Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myhU4_cXaEsYGNtICLAW0Q.jpeg" /></figure><p>This weekend, I was hacking away on a comments system for my SaaS app Lean Steps, and about half-way through I realized that it would make a great blog post. So, here we are!</p><p>In this first post, we’ll start our comments system by building a Vue.js component. Then in the next few installments, we can style it with Tailwind CSS and wire it up to a Laravel backend to persist our comments.</p><p>Let’s dive right in and get to work!</p><h3>The Set Up</h3><p>We’ll be using Laravel for our backend, so we can start by setting up a new Laravel project. To do that we can navigate to where we want to store our project in our terminal and then run laravel new comments (feel free to call the project whatever you&#39;d like).</p><p>Once our project is done installing, we’ll need to update some of the .env variables. Opening up our project, we can see the .env file in the root of our project. Inside we&#39;ll update the APP_NAME and APP_URL to &quot;Comments Demo&quot; and &quot;http://comments.test&quot; respectively.</p><p>In case you were wondering, I’m getting that URL from Laravel Valet. If you’re interested in getting set up with that, check out their docs <a href="https://laravel.com/docs/5.6/valet">here</a>.</p><p>Now we can update our database details. I have a generic demo database set up that I use for all of my quick projects. I think it’s nice because I don’t have to spin up a new database for each project.</p><p>If you don’t already have one set up, you can run mysql -uroot -p to sign into MySQL and then run create database &lt;database-name&gt;; to create a new database.</p><p>With that setup, in our .env we can update our DB_DATABASE to match our database name. Our DB_USERNAME can be set to root, and we can leave our DB_PASSWORD blank.</p><p>We’ll be using Laravel’s default authentication scaffolding so we can record which users left comments. So, we’ll scaffold that by running php artisan make:auth.</p><p>Now, we’re ready to migrate our database. To do that, we’ll run php artisan migrate from the command line.</p><p>Onto our JavaScript build, we’ll initialize all of our dependencies by running yarn. Then we can add in Tailwind CSS by following the installation instructions provided in their <a href="https://tailwindcss.com/docs/installation/">docs</a>.</p><p>Finally, we’ll initialize our git repository and commit all of this set up by running git init, git add ., and git commit -m &quot;initial commit&quot;.</p><p>That’ll get us up and running for this project. Now let’s start building our comments component.</p><h3>Scaffolding The Component</h3><p>We can start building our comments component by running npm run watch so our JavaScript changes get compiled as we work. Next, we&#39;ll hop into our home.blade.php file and clear out the existing code between the @section()tags, so we have some room to add our comments.</p><p>In our browser, we can quickly run through the register flow to create an account so that we can see the home.blade.php template in action. With everything cleared out we should see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/0*rBvlZIeARYlhfJhW.png" /></figure><p>With that setup, we can head over to our resources/asset/js/componentsdirectory and add a new Vue file called CommentsManager.vue. Inside of there, we&#39;ll scaffold it out with the following:</p><pre>&lt;template&gt;<br>    &lt;div&gt;<br>        &lt;h1&gt;Hello World&lt;/h1&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>    export default {<br>        data: function() {<br>            return {</pre><pre>          }<br>        },<br>    }<br>&lt;/script&gt;</pre><p>Nice! Now, we can register our CommentsManager component in our app.js file like so:</p><pre>Vue.component(&#39;comments-manager&#39;, require(&#39;./components/CommentsManager.vue&#39;));</pre><p>Finally, we can add our component to the home.blade.php file so we can see it in our browser. To do that, we&#39;ll add the component in between the @section() tags like this:</p><pre>@extends(&#39;layouts.app&#39;)</pre><pre>@section(&#39;content&#39;)<br>    &lt;comments-manager&gt;&lt;/comments-manager&gt;<br>@endsection</pre><p>Back in our browser, we can now see that our component is being rendered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*FFj120qOFMunTMAp.png" /></figure><p>Not the prettiest UI just yet, but we’ll get there!</p><h3>Showing Comments</h3><p>With that all set up, let’s start showing some comments. Inside of our CommentsManager&#39;s data property, we can add an Array for comments. Inside, we&#39;ll add a basic comment with some details we&#39;re going to need.</p><pre>data: function() {<br>    return {<br>        comments: [<br>            {<br>                id: 1,<br>                body: &quot;How&#39;s it going?&quot;,<br>                edited: false,<br>                created_at: new Date().toLocaleString(),<br>                author: {<br>                    id: 1,<br>                    name: &#39;Nick Basile&#39;,<br>                }<br>            }<br>        ]<br>    }<br>},</pre><p>Now that we have some data to work with we can start showing it on the page. At this point, we have a choice to make. While we could keep all of our logic contained within the CommentsManager component, we&#39;d end up having to write some weird methods to parse each comment&#39;s details. So, let&#39;s make another component for each comment.</p><p>In the same directory as CommentsManager, we can create a new Vue file called CommentItem. We can scaffold it the same way as CommentsManager.</p><pre>&lt;template&gt;<br>    &lt;div&gt;<br>    <br>    &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>    export default {<br>        data: function() {<br>            return {<br>                <br>          }<br>        },<br>    }<br>&lt;/script&gt;</pre><p>Now, let’s pass through a comment prop with all of the comment&#39;s data and then add it to the template.</p><pre>&lt;template&gt;<br>    &lt;div&gt;<br>        &lt;div&gt;<br>            &lt;p&gt;{{comment.body}}&lt;/p&gt;<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>            &lt;p&gt;{{comment.author.full_name}} &lt;span&gt;&amp;bull;&lt;/span&gt;{{ comment.created_at}}&lt;/p&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>    export default {<br>        props: {<br>            comment: {<br>                required: true,<br>                type: Object,<br>            }<br>        },<br>        data: function() {<br>            return {</pre><pre>          }<br>        },<br>    }<br>&lt;/script&gt;</pre><p>With our component in place, we can register it in our CommentsManager and start showing the comments. Right below our opening script tag, we can import our CommentItem. Then we can add a components property to CommentsManagerand register our CommentItem. To wrap this up, we&#39;ll add our comment to the template, add a v-for and :key directives, and add our comment prop.</p><pre>&lt;template&gt;<br>    &lt;div&gt;<br>        &lt;div&gt;<br>            &lt;comment v-for=&quot;comment in comments&quot;<br>                     :key=&quot;comment.id&quot;<br>                     :comment=&quot;comment&quot;&gt;<br>            &lt;/comment&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>    import comment from &#39;./CommentItem&#39;<br>    export default {<br>        components: {<br>            comment<br>        },<br>        data: function() {<br>            return {<br>                comments: [<br>                    {<br>                        id: 1,<br>                        body: &quot;How&#39;s it going?&quot;,<br>                        edited: false,<br>                        created_at: new Date().toLocaleString(),<br>                        author: {<br>                            id: 1,<br>                            name: &#39;Nick Basile&#39;,<br>                        }<br>                    }<br>                ]<br>          }<br>        },<br>    }<br>&lt;/script&gt;</pre><p>Now our page is starting to come to life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gADsJiuQmAAGYEJ9.png" /></figure><p>Let’s keep working on out CommentItem component and add the ability to edit a comment.</p><h3>Editing a Comment</h3><p>As we build the edit functionality, it’s important to remember that we don’t want to let just anybody edit a comment. We only want the author to edit it. To make that happen, we’ll need to pass the current user to our CommentItem.</p><p>For that, we’ll need to add a user prop to both our components and then add pass through the authenticated user. We can go ahead and add that prop like this;</p><pre>//CommentsManager<br>&lt;comment v-for=&quot;comment in comments&quot;<br>         :key=&quot;comment.id&quot;<br>         :user=&quot;user&quot;<br>         :comment=&quot;comment&quot;&gt;<br>&lt;/comment&gt;<br>...<br>props: {<br>    user: {<br>        required: true,<br>        type: Object,<br>    }<br>},</pre><pre>//CommentItem<br>props: {<br>    user: {<br>        required: true,<br>        type: Object,<br>    },<br>    comment: {<br>        required: true,<br>        type: Object,<br>    }<br>},</pre><pre>//home.blade.php<br>&lt;comments-manager :user=&quot;{{ auth()-&gt;user() }}&quot;&gt;&lt;/comments-manager&gt;</pre><p>Now in our CommentItem, we can add a computed property to check if the current user can edit this comment.</p><pre>computed: {<br>    editable() {<br>        return this.user.id === this.comment.author.id;<br>    }<br>}</pre><p>It’s a pretty simple check, but having it in a computed property will make our template much more readable.</p><p>Now we can add an edit button for our comment author. Right below our comment.body, we can add the button.</p><pre>&lt;div&gt;<br>    &lt;p&gt;{{comment.body}}&lt;/p&gt;<br>    &lt;button v-if=&quot;editable&quot;&gt;Edit&lt;/button&gt;<br>&lt;/div&gt;</pre><p>With that v-if in place, we can be sure that only the author will be able to click that button. Let&#39;s add another comment now so we can see both states in action. So in the CommentsManager inside of comments, we can add another Object.</p><pre>comments: [<br>    {<br>        id: 1,<br>        body: &quot;How&#39;s it going?&quot;,<br>        edited: false,<br>        created_at: new Date().toLocaleString(),<br>        author: {<br>            id: 1,<br>            name: &#39;Nick Basile&#39;,<br>        }<br>    },<br>    {<br>        id: 2,<br>        body: &quot;Pretty good. Just making a painting.&quot;,<br>        edited: false,<br>        created_at: new Date().toLocaleString(),<br>        author: {<br>            id: 2,<br>            name: &#39;Bob Ross&#39;,<br>        }<br>    }<br>]</pre><p>Looking at our page, we can see that we can’t edit Bob’s comment because we’re not the author of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NGIm1ClGFg9Lwio2.png" /></figure><p>That’s pretty awesome. Now, let’s get to work editing our comment.</p><p>We’ll start by adding a state property to our CommentItem&#39;s component&#39;s dataso we can keep track of when we&#39;re editing. Let&#39;s also add a updatedCommentproperty so we can keep track of our changes.</p><pre>data: function() {<br>    return {<br>        state: &#39;default&#39;,<br>        data: {<br>            body: this.comment.body,<br>        }<br>  }<br>},</pre><p>Since this is a pretty simple state, I’ll go ahead and use a String. But, feel free to use a Boolean if you’d like. For a more in-depth look at when to use which, check out my previous <a href="https://nick-basile.com/blog/post/managing-local-state-in-vuejs-components">blog post</a> about it.</p><p>Initializing our data.body with the value from the comment.body allows us to populate our edit form with the correct initial data.</p><p>Now, we’ll need to wire up our edit button to toggle the state. We can simply bind a click event that sets the state to editing.</p><pre>&lt;button v-if=&quot;editable&quot; @click=&quot;state = &#39;editing&#39;&quot;&gt;Edit&lt;/button&gt;</pre><p>With that hooked up, let’s add in our edit form and make sure we’re toggling our read and edit states.</p><pre>&lt;template&gt;<br>    &lt;div&gt;<br>        &lt;div v-show=&quot;state === &#39;default&#39;&quot;&gt;<br>            &lt;div&gt;<br>                &lt;p&gt;{{comment.body}}&lt;/p&gt;<br>                &lt;button v-if=&quot;editable&quot; @click=&quot;state = &#39;editing&#39;&quot;&gt;Edit&lt;/button&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>                &lt;p&gt;{{comment.author.full_name}} &lt;span&gt;&amp;bull;&lt;/span&gt;{{ comment.created_at}}&lt;/p&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div v-show=&quot;state === &#39;editing&#39;&quot;&gt;<br>            &lt;div&gt;<br>                &lt;h3&gt;Update Comment&lt;/h3&gt;<br>            &lt;/div&gt;<br>            &lt;textarea v-model=&quot;data.body&quot;<br>                      placeholder=&quot;Update comment&quot;<br>                      class=&quot;border&quot;&gt;<br>            &lt;/textarea&gt;<br>            &lt;div&gt;<br>                &lt;button&gt;Update&lt;/button&gt;<br>                &lt;button&gt;Cancel&lt;/button&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;</pre><p>Everything here is pretty straight-forward. We have two divs that we toggle when the state changes. The first div has our read state from earlier, while the second contains a textarea and some buttons. Let&#39;s wire up the cancel button first so we can toggle the editing state.</p><p>We can add a method called resetEdit that will toggle the state and reset the data.body information. Then we&#39;ll bind that to our cancel button.</p><pre>//Template<br>&lt;button @click=&quot;resetEdit&quot;&gt;Cancel&lt;/button&gt;<br>...</pre><pre>//Vue Instance<br>methods: {<br>    resetEdit() {<br>        this.state = &#39;default&#39;;<br>        this.data.body = this.comment.body;<br>    }<br>}</pre><p>Now we can make all the changes we want and leave before saving them.</p><p>Let’s continue by persisting our edits. We’ll make another method and call it saveEdit(). We can then bind that to our save button.</p><p>Here we have a couple of choices for bubbling our changes back up to the parent component where comments live. We could use $parent.comments to access them directly, or we could directly change our comment prop. These aren&#39;t the best options though, because they tightly couple our components together. That isn&#39;t always the worst thing in the world, but let&#39;s use events for a more &quot;proper&quot; approach.</p><p>In our saveEdit method, we&#39;ll set the state back to its default value, and we&#39;ll $emit a comment-updated event with the data we&#39;ll need to make this edit. Then in our CommentsManager, we&#39;ll have an updateComment method that will get called when our event fires.</p><pre>//CommentItem</pre><pre>//Template<br>&lt;button @click=&quot;saveEdit&quot;&gt;Update&lt;/button&gt;</pre><pre>//Script<br>saveEdit() {<br>    this.state = &#39;default&#39;;</pre><pre>    this.$emit(&#39;comment-updated&#39;, {<br>        &#39;id&#39;: this.comment.id,<br>        &#39;body&#39;: this.data.body,<br>    });<br>}</pre><pre>//CommentsManager</pre><pre>//Template<br>&lt;comment v-for=&quot;comment in comments&quot;<br>         :key=&quot;comment.id&quot;<br>         :user=&quot;user&quot;<br>         :comment=&quot;comment&quot;<br>         @comment-updated=&quot;updateComment($event)&quot;&gt;<br>&lt;/comment&gt;</pre><pre>//Script<br>methods: {<br>    updateComment($event) {<br>        let index = this.comments.findIndex((element) =&gt; {<br>            return element.id === $event.id;<br>        });</pre><pre>        this.comments[index].body = $event.body;<br>    }<br>}</pre><p>Hopping into our browser, we can see that our comment is getting updated now.</p><h3>Deleting a Comment</h3><p>With this same approach, we can also add the functionality to delete a comment. Let’s add a delete button to our template and wire up an event.</p><pre>//CommentItem</pre><pre>//Template<br>&lt;div&gt;<br>    &lt;button @click=&quot;saveEdit&quot;&gt;Update&lt;/button&gt;<br>    &lt;button @click=&quot;resetEdit&quot;&gt;Cancel&lt;/button&gt;<br>    &lt;button @click=&quot;deleteComment&quot;&gt;Delete&lt;/button&gt;<br>&lt;/div&gt;</pre><pre>//Script<br>deleteComment() {<br>    this.$emit(&#39;comment-deleted&#39;, {<br>        &#39;id&#39;: this.comment.id,<br>    });<br>}</pre><pre>//Comments Manager</pre><pre>//Template<br>&lt;comment v-for=&quot;comment in comments&quot;<br>         :key=&quot;comment.id&quot;<br>         :user=&quot;user&quot;<br>         :comment=&quot;comment&quot;<br>         @comment-updated=&quot;updateComment($event)&quot;<br>         @comment-deleted=&quot;deleteComment($event)&quot;&gt;<br>&lt;/comment&gt;</pre><pre>//Script<br>deleteComment($event) {<br>    let index = this.comments.findIndex((element) =&gt; {<br>        return element.id === $event.id;<br>    });</pre><pre>    this.comments.splice(index, 1);<br>}</pre><p>Once we get the hang of using events to manipulate data, it gets pretty easy to build functionality like this. Now that we can edit and delete our comments let’s add a form for adding new comments.</p><h3>Adding Comments</h3><p>If you’ve been keeping score at home, we’re down to our final CRUD action: creating new comments. We’ll keep things simple and add a form directly to our CommentsManager.</p><p>Right above our comment v-for we can add a simple form that looks a look like our edit form.</p><pre>&lt;template&gt;<br>    &lt;div&gt;<br>        &lt;div&gt;<br>            &lt;div&gt;<br>                &lt;h2&gt;Comments&lt;/h2&gt;<br>            &lt;/div&gt;<br>            &lt;textarea placeholder=&quot;Add a comment&quot;<br>                          class=&quot;border&quot;&gt;<br>              &lt;/textarea&gt;<br>            &lt;div&gt;<br>                &lt;button&gt;Save&lt;/button&gt;<br>                &lt;button&gt;Cancel&lt;/button&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>            &lt;comment v-for=&quot;comment in comments&quot;<br>                     :key=&quot;comment.id&quot;<br>                     :user=&quot;user&quot;<br>                     :comment=&quot;comment&quot;<br>                     @comment-updated=&quot;updateComment($event)&quot;<br>                     @comment-deleted=&quot;deleteComment($event)&quot;&gt;<br>            &lt;/comment&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;</pre><p>To start adding new offers, we’ll need to add a saveComment method, add a data.body property to our data, and add a v-model to our textarea.</p><pre>//Template<br> &lt;div&gt;<br>    &lt;div&gt;<br>        &lt;h2&gt;Comments&lt;/h2&gt;<br>    &lt;/div&gt;<br>    &lt;textarea v-model=&quot;data.body&quot;<br>              placeholder=&quot;Add a comment&quot;<br>              class=&quot;border&quot;&gt;<br>    &lt;/textarea&gt;<br>    &lt;div&gt;<br>        &lt;button @click=&quot;saveComment&quot;&gt;Save&lt;/button&gt;<br>        &lt;button&gt;Cancel&lt;/button&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><pre>//Script<br>saveComment() {<br>    let newComment = {<br>        id: this.comments[this.comments.length - 1].id + 1,<br>        body: this.data.body,<br>        edited: false,<br>        created_at: new Date().toLocaleString(),<br>        author: {<br>            id: this.user.id,<br>            name: this.user.name,<br>        }<br>    }</pre><pre>    this.comments.push(newComment);<br>    <br>    this.data.body = &#39;&#39;;<br>}</pre><p>Inside of saveComment we build up our newComment with the data from our form, our user, and elsewhere. Notably, we&#39;re not just setting the id to the length of the comments Array. This could lead to collisions in our key if we deleted the first comment and then tried to add another one. This approach guarantees that we won&#39;t have any collisions.</p><p>If we head on over to our browser, we can see that our saveComment method is working just like we&#39;d expect.</p><h3>The Wrap-Up</h3><p>With our basic CRUD actions in place, our comments system is coming together! But, right now it’s a little hard to look at. In the <a href="https://medium.com/@nickjbasile/building-a-comments-system-with-vue-js-laravel-and-tailwind-css-part-ii-2d682efb0a31">next post</a>, we’ll style everything nicely with Tailwind CSS.</p><p>If you’d like an overview of the components we built today, you can see them at on our GitHub repo <a href="https://github.com/nickbasile/comments-demo/pull/1/files">here</a>. As always, feel free to ask me any questions on <a href="https://twitter.com/nickjbasile">Twitter</a>. And until next time, happy coding!</p><p><em>P.S. Need more help? I offer free 30 minute </em><a href="https://calendly.com/nicholas-basile/office-hours"><em>coaching sessions</em></a><em> to help you solve quick problems. For larger projects, I can help you plan, design, or develop the </em><a href="https://launchshop.io/"><em>software you need</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e24e8518ee3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving A Typecasting “Gotcha” When Passing Data From Laravel To Vue.js]]></title>
            <link>https://nickjbasile.medium.com/solving-a-typecasting-gotcha-when-passing-data-from-laravel-to-vue-js-ae91330533ac?source=rss-12d3411267e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae91330533ac</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[type-casting]]></category>
            <dc:creator><![CDATA[Nick Basile]]></dc:creator>
            <pubDate>Wed, 11 Apr 2018 22:23:16 GMT</pubDate>
            <atom:updated>2018-12-04T15:35:28.226Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AxjCepQA1JfL6J1mvIslhg.jpeg" /></figure><p>When working with Laravel and Vue.js, a typical pattern for initializing our Vue components with data is to pass controller data from Laravel into Vue props. Doing this allows us to leverage Laravel’s controllers to manage our data in an MVC fashion.</p><p>While this is a common practice, I’ve run into a tricky casting issue when I’m working with filtered data. I’ll show you how to re-create the problem, and solve it so you can avoid it in your projects.</p><h3>Set Up</h3><p>We’ll start with a regular Laravel project. For a guide on setting that up, you can check out <a href="https://nick-basile.com/blog/post/how-to-configure-a-new-laravel-55-project">this checklist</a>. Beyond our basic set up, we’ll need to fake some data in our HomeController.php.</p><p>In this file, we’ll add an Array of $results in the index function.</p><pre>public function index()<br>{<br>    $results = [<br>        [<br>            &#39;id&#39; =&gt; 1,<br>            &#39;name&#39; =&gt; &#39;Foo&#39;,<br>            &#39;status&#39; =&gt; &#39;active&#39;,<br>        ],<br>        [<br>            &#39;id&#39; =&gt; 2,<br>            &#39;name&#39; =&gt; &#39;Bar&#39;,<br>            &#39;status&#39; =&gt; &#39;inactive&#39;,<br>        ],<br>        [<br>            &#39;id&#39; =&gt; 3,<br>            &#39;name&#39; =&gt; &#39;Baz&#39;,<br>            &#39;status&#39; =&gt; &#39;active&#39;,<br>        ],<br>        [<br>            &#39;id&#39; =&gt; 4,<br>            &#39;name&#39; =&gt; &#39;Biz&#39;,<br>            &#39;status&#39; =&gt; &#39;inactive&#39;,<br>        ],<br>    ];<br>}</pre><p>Next, we’ll turn this Array into a Collection so we can apply the transforms that cause the issue.</p><pre>public function index()<br>{<br>    $results = collect([<br>        [<br>            &#39;id&#39; =&gt; 1,<br>            &#39;name&#39; =&gt; &#39;Foo&#39;,<br>            &#39;status&#39; =&gt; &#39;active&#39;,<br>        ],<br>        [<br>            &#39;id&#39; =&gt; 2,<br>            &#39;name&#39; =&gt; &#39;Bar&#39;,<br>            &#39;status&#39; =&gt; &#39;inactive&#39;,<br>        ],<br>        [<br>            &#39;id&#39; =&gt; 3,<br>            &#39;name&#39; =&gt; &#39;Baz&#39;,<br>            &#39;status&#39; =&gt; &#39;active&#39;,<br>        ],<br>        [<br>            &#39;id&#39; =&gt; 4,<br>            &#39;name&#39; =&gt; &#39;Biz&#39;,<br>            &#39;status&#39; =&gt; &#39;inactive&#39;,<br>        ],<br>    ]);<br>}</pre><p>Then we’ll return our home view with this data so we can use it in our Vue component.</p><pre>public function index()<br>{<br>    $results = collect([<br>        [<br>            &#39;id&#39; =&gt; 1,<br>            &#39;name&#39; =&gt; &#39;Foo&#39;,<br>            &#39;status&#39; =&gt; &#39;active&#39;,<br>        ],<br>        [<br>            &#39;id&#39; =&gt; 2,<br>            &#39;name&#39; =&gt; &#39;Bar&#39;,<br>            &#39;status&#39; =&gt; &#39;inactive&#39;,<br>        ],<br>        [<br>            &#39;id&#39; =&gt; 3,<br>            &#39;name&#39; =&gt; &#39;Baz&#39;,<br>            &#39;status&#39; =&gt; &#39;active&#39;,<br>        ],<br>        [<br>            &#39;id&#39; =&gt; 4,<br>            &#39;name&#39; =&gt; &#39;Biz&#39;,<br>            &#39;status&#39; =&gt; &#39;inactive&#39;,<br>        ],<br>    ]);<br>    <br>    return view(&#39;home&#39;, compact(&#39;results&#39;));<br>}</pre><p>With our data taken care of, we can focus on adding our Vue component.</p><p>Inside of our components folder, we can add a WhereExample.vue file. In here, we&#39;ll simply accept a results prop and render it with a v-for.</p><pre>&lt;template&gt;<br>    &lt;div&gt;<br>        &lt;p v-for=&quot;result in results&quot; :key=&quot;result.id&quot;&gt;{{ result.name }}&lt;/p&gt;&lt;br/&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>    export default {<br>        props: {<br>            results: {<br>               type: Array,<br>               required: true,<br>            },<br>        },<br>    }<br>&lt;/script&gt;</pre><p>Now we can register this in our app.js file and add it to home.blade.php.</p><pre>// app.js<br>Vue.component(&#39;where-example&#39;, require(&#39;./components/WhereExample.vue&#39;));</pre><pre>//home.blade.php<br>&lt;where-example :results=&quot;{{ $results }}&quot;&gt;&lt;/where-example&gt;</pre><p>With our set up out of the way, let’s dive into the issue.</p><h3>The Problem</h3><p>Notice that when we defined our results prop in our Vue component, we specified that we&#39;re expecting an Array. Right now, if we check out what&#39;s happening in our Vue Devtools, we can see that everything is working as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*07MmPAGoMHXXVgst.png" /></figure><p>Now for the problem. When we want to filter our data in the controller, we’ll see that our prop is being cast as an Object instead of as an Array. To do that, we’ll add a -&gt;where() clause to our $results Collection to only show the active results.</p><pre>public function index()<br>{<br>    $results = collect([<br>        [<br>            &#39;id&#39; =&gt; 1,<br>            &#39;name&#39; =&gt; &#39;Foo&#39;,<br>            &#39;status&#39; =&gt; &#39;active&#39;,<br>        ],<br>        [<br>            &#39;id&#39; =&gt; 2,<br>            &#39;name&#39; =&gt; &#39;Bar&#39;,<br>            &#39;status&#39; =&gt; &#39;inactive&#39;,<br>        ],<br>        [<br>            &#39;id&#39; =&gt; 3,<br>            &#39;name&#39; =&gt; &#39;Baz&#39;,<br>            &#39;status&#39; =&gt; &#39;active&#39;,<br>        ],<br>        [<br>            &#39;id&#39; =&gt; 4,<br>            &#39;name&#39; =&gt; &#39;Biz&#39;,<br>            &#39;status&#39; =&gt; &#39;inactive&#39;,<br>        ],<br>    ])<br>    -&gt;where(&#39;status&#39;, &#39;active&#39;);<br>    <br>    return view(&#39;home&#39;, compact(&#39;results&#39;));<br>}</pre><p>Hopping back over to our Vue Devtools, we can see that our Array has turned into an Object! And, we can see that Vue provides a helpful error in the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*3Hbi0WyXWVJi2ut7.png" /></figure><p>This is a pretty big deal. Imagine that we wanted to show a message if we didn’t have any results. With an Array, we could easily use .length to see if there were any results. But, we can&#39;t use .length with an Object. All of a sudden, our Vue component would be broken!</p><p>That’s just one example, but there are plenty of features we could build expecting an Array as our data that would break if they received an Object. Fortunately, there is a pretty simple fix for this issue.</p><h3>The Solution</h3><p>The reason the -&gt;where() clause changes our Array into an Object is because it maintains the index of the filtered results. When Vue receives this data with non-linear indexes, it assumes that this must be an Object.</p><p>While this is pretty smart and even desirable in most cases, it does leave us in a pickle here. But, we can use the -&gt;values() clause after -&gt;where() to reset the indexes to their linear values.</p><p>Doing this makes our results look like an Array again to Vue. So, in our example, we can add -&gt;values() to the end of our $results Collection and everything will start working again.</p><pre>public function index()<br>{<br>    $results = collect([<br>        [<br>            &#39;id&#39; =&gt; 1,<br>            &#39;name&#39; =&gt; &#39;Foo&#39;,<br>            &#39;status&#39; =&gt; &#39;active&#39;,<br>        ],<br>        [<br>            &#39;id&#39; =&gt; 2,<br>            &#39;name&#39; =&gt; &#39;Bar&#39;,<br>            &#39;status&#39; =&gt; &#39;inactive&#39;,<br>        ],<br>        [<br>            &#39;id&#39; =&gt; 3,<br>            &#39;name&#39; =&gt; &#39;Baz&#39;,<br>            &#39;status&#39; =&gt; &#39;active&#39;,<br>        ],<br>        [<br>            &#39;id&#39; =&gt; 4,<br>            &#39;name&#39; =&gt; &#39;Biz&#39;,<br>            &#39;status&#39; =&gt; &#39;inactive&#39;,<br>        ],<br>    ])<br>    -&gt;where(&#39;status&#39;, &#39;active&#39;)<br>    -&gt;values();<br>    <br>    return view(&#39;home&#39;, compact(&#39;results&#39;));<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/0*vXQ0YJC1Q-coC6wO.png" /></figure><p>Now we have the filtered results working the way we would expect.</p><h3>The Wrap-Up</h3><p>I’ve certainly spent some time trying to figure out why my Vue components have stopped working because of a simple -&gt;where() clause in my controller. This is often tricky to debug because the issue is so far removed from where it shows up.</p><p>When I first encountered this issue, I probably wouldn’t have figured it out if I hadn’t been using Vue <a href="https://vuejs.org/v2/style-guide/#Prop-definitions-essential">best practices</a> by defining my prop definitions. It goes to show how helpful they can be in a tricky situation.</p><p>I hope this post will help you avoid, or at least debug, this issue in your projects. As always, feel free to ask me any questions on <a href="https://twitter.com/nickjbasile">Twitter</a>. And until next time, happy researching!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae91330533ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Local State In Vue.js Components]]></title>
            <link>https://itnext.io/managing-local-state-in-vue-js-components-d5d92fb432?source=rss-12d3411267e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5d92fb432</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Nick Basile]]></dc:creator>
            <pubDate>Thu, 05 Apr 2018 11:44:03 GMT</pubDate>
            <atom:updated>2018-12-04T15:35:43.653Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5BefaNBsqn3zSInnOcNleg.jpeg" /></figure><blockquote><a href="https://www.linkedin.com/cws/share?url=https%3A%2F%2Fitnext.io%2Fmanaging-local-state-in-vue-js-components-d5d92fb432%3Futm_source%3Dmedium_sharelink%26utm_medium%3Dsocial%26utm_campaign%3Dbuffer"><em>Clic</em>k here to share this article on LinkedIn »</a></blockquote><p>Typically when we hear Vue.js and state management, our minds immediately jump to Vuex or another robust state management solution. However, the majority of our state management doesn’t happen on such a large scale. Instead, it’s tucked away inside of our Vue components.</p><p>If you’re still scratching your head about what I’m talking about, let’s take a look at an example of local state in action.</p><pre>&lt;template&gt;<br>    &lt;div&gt;<br>        &lt;div v-if=&quot;state === &#39;default&#39;&quot;&gt;<br>            &lt;h1&gt;Default State&lt;/h1&gt;<br>        &lt;/div&gt;<br>        &lt;div v-else&gt;<br>            &lt;h1&gt;Every Other State&lt;/h1&gt;        <br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>    export default {<br>        data: function () {<br>            return {<br>                state: &#39;default&#39;<br>            }<br>        }<br>    }        <br>&lt;/script&gt;</pre><p>In our data, we have a state property that we&#39;re using to keep track of the different states of our component. Pretty simple, right?</p><p>I’ve noticed that in the Vue community, we typically manage this local state with two different patterns. The first, like in the example above, relies on a descriptive String. The other pattern relies on a nested Object and booleans, like this:</p><pre>&lt;template&gt;<br>    &lt;div&gt;<br>        &lt;div v-if=&quot;state.visbility&quot;&gt;<br>            &lt;h1&gt;Default State&lt;/h1&gt;<br>        &lt;/div&gt;<br>        &lt;div v-else&gt;<br>            &lt;h1&gt;Every Other State&lt;/h1&gt;        <br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>    export default {<br>        data: function () {<br>            return {<br>                state: {<br>                    visiblity: true<br>                }<br>            }<br>        }<br>    }        <br>&lt;/script&gt;</pre><p>Both of these methods work pretty well, but let’s take a closer look at each of them and examine their pros and cons.</p><h3>The Set-Up</h3><p>Before we dive right in, let’s get ourselves set up with a little loading notification component. To get everything up and running as quickly as possible, we’ll use the Vue CDN instead of a full-build.</p><p>Let’s start with a blank index.html file with our Vue CDN included.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;Local State Management&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now, let’s add the Tailwind CSS and Font Awesome CDNs, so we have a better-looking example.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;Local State Management&lt;/title&gt;<br>    &lt;link href=&quot;https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css&quot; rel=&quot;stylesheet&quot;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;script defer src=&quot;https://use.fontawesome.com/releases/v5.0.9/js/all.js&quot; integrity=&quot;sha384-8iPTk2s/jMVj81dnzb/iFR2sdA7u06vHJyyLlAd4snFpCl/SnyUjRrbdJsw1pGIl&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Great! Now, we can scaffold out some HTML. For this example, we need a simple UI card with a little loader component in the header.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;Local State Management&lt;/title&gt;<br>    &lt;link href=&quot;https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css&quot; rel=&quot;stylesheet&quot;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div&gt;<br>        &lt;div&gt;<br>          &lt;h1&gt;A Cool Card&lt;/h1&gt;<br>          &lt;h4 id=&quot;loader&quot;&gt;<br>            &lt;i class=&quot;fas fa-circle-notch fa-spin&quot;&gt;&lt;/i&gt; Loading...<br>          &lt;/h4&gt;<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>          &lt;p&gt;Lorem Khaled Ipsum is a major key to success. They will try to close the door on you, just open it. Give thanks to the most high. Eliptical talk. Celebrate success right, the only way, apple. Another one. The weather is amazing, walk with me through the pathway of more success. Take this journey with me, Lion! Watch your back, but more importantly when you get out the shower, dry your back, it’s a cold world out there.&lt;/p&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>    <br>    &lt;script defer src=&quot;https://use.fontawesome.com/releases/v5.0.9/js/all.js&quot; integrity=&quot;sha384-8iPTk2s/jMVj81dnzb/iFR2sdA7u06vHJyyLlAd4snFpCl/SnyUjRrbdJsw1pGIl&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>If we take a look at this in our browser, we can see that all of the pieces are there, but it’s not looking too good.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y7lzGsg_LpcoeHTv.png" /></figure><p>Let’s add some Tailwind classes to center our card, make it more prominent, and style the typography better.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;Local State Management&lt;/title&gt;<br>    &lt;link href=&quot;https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css&quot; rel=&quot;stylesheet&quot;&gt;<br>&lt;/head&gt;<br>&lt;body class=&quot;flex item-center justify-center h-screen bg-blue-lightest font-sans&quot;&gt;<br>    &lt;div class=&quot;p-6 bg-white rounded shadow max-w-md m-auto&quot;&gt;<br>        &lt;div class=&quot;flex justify-between items-center mb-4&quot;&gt;<br>          &lt;h1 class=&quot;text-black&quot;&gt;A Cool Card&lt;/h1&gt;<br>          &lt;h4 id=&quot;loader&quot; class=&quot;font-light text-blue&quot;&gt;<br>            &lt;i class=&quot;fas fa-circle-notch fa-spin mr-1&quot;&gt;&lt;/i&gt; Loading...<br>          &lt;/h4&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;text-grey-dark leading-normal&quot;&gt;<br>          &lt;p&gt;Lorem Khaled Ipsum is a major key to success. They will try to close the door on you, just open it. Give thanks to the most high. Eliptical talk. Celebrate success right, the only way, apple. Another one. The weather is amazing, walk with me through the pathway of more success. Take this journey with me, Lion! Watch your back, but more importantly when you get out the shower, dry your back, it’s a cold world out there.&lt;/p&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;</pre><pre>    &lt;script defer src=&quot;https://use.fontawesome.com/releases/v5.0.9/js/all.js&quot; integrity=&quot;sha384-8iPTk2s/jMVj81dnzb/iFR2sdA7u06vHJyyLlAd4snFpCl/SnyUjRrbdJsw1pGIl&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>It’s amazing what a little bit of CSS can do for a UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s7WOH7EfsiDDxMHm.png" /></figure><p>Finally, let’s scaffold out the Vue.js code that we can share between our String and Boolean state methods.</p><p>We’ll start by initializing a Vue instance, setting the el, converting the template to be data-driven, and stubbing out the data and computed property we&#39;ll need.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;Local State Management&lt;/title&gt;<br>    &lt;link href=&quot;https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css&quot; rel=&quot;stylesheet&quot;&gt;<br>&lt;/head&gt;<br>&lt;body class=&quot;flex item-center justify-center h-screen bg-blue-lightest font-sans&quot;&gt;<br>    &lt;div class=&quot;p-6 bg-white rounded shadow max-w-md m-auto&quot;&gt;<br>        &lt;div class=&quot;flex justify-between items-center mb-4&quot;&gt;<br>          &lt;h1 class=&quot;text-black&quot;&gt;A Cool Card&lt;/h1&gt;<br>          &lt;h4 v-if=&quot;state&#39;&quot; id=&quot;loader&quot; class=&quot;font-light text-blue&quot;&gt;<br>            &lt;i v-show=&quot;state&quot; class=&quot;fas fa-circle-notch fa-spin mr-1&quot;&gt;&lt;/i&gt;<br>            &lt;i v-show=&quot;state&quot; class=&quot;far fa-check-circle mr-1&quot;&gt;&lt;/i&gt;<br>            {{ header }}<br>          &lt;/h4&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;text-grey-dark leading-normal&quot;&gt;<br>          &lt;p&gt;Lorem Khaled Ipsum is a major key to success. They will try to close the door on you, just open it. Give thanks to the most high. Eliptical talk. Celebrate success right, the only way, apple. Another one. The weather is amazing, walk with me through the pathway of more success. Take this journey with me, Lion! Watch your back, but more importantly when you get out the shower, dry your back, it’s a cold world out there.&lt;/p&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;</pre><pre>    &lt;script defer src=&quot;https://use.fontawesome.com/releases/v5.0.9/js/all.js&quot; integrity=&quot;sha384-8iPTk2s/jMVj81dnzb/iFR2sdA7u06vHJyyLlAd4snFpCl/SnyUjRrbdJsw1pGIl&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js&quot;&gt;&lt;/script&gt;<br>    &lt;script&gt;<br>      var shoppingList = new Vue({<br>        el: &#39;#loader&#39;,<br>        data: {<br>          state: null<br>        },<br>        computed: {<br>          header() {</pre><pre>            return &#39;&#39;;<br>          }<br>        }<br>      })<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Bada bing bada boom, we’ve got ourselves an excellent component to use. Now let’s see the different ways of managing our state.</p><h3>Boolean Method</h3><p>First up, the Boolean method. This was the first way to manage state that I figured out, and it makes sense. I’ve found that I typically use states to work with Vue’s conditional directives, so I would frequently see myself toggling state booleans.</p><p>This is a little abstract, so let’s put this into action in our component. We’ll start by setting our state property to an Object, and then add a few boolean properties for our different states.</p><pre>data: {<br>    state: {<br>        default: true,<br>        loading: false,<br>        done: false<br>    }<br>}</pre><p>As you can see, we’re being explicit about what states we’d like to be managing. I think that this is the most significant benefit of this approach — you can see all of the possible component states by looking at your state Object.</p><p>This can be super useful if you’re working with a large, complicated component. Although, if you find yourself managing too many state properties or a nested state Object, then that might be a code-smell for refactoring into smaller components.</p><p>Let’s finish the rest of our component so it can respond to our new state data. We can add some logic to our header computed property to return an appropriate String according to the state.</p><pre>computed: {<br>  header() {<br>       if(this.state.loading) {<br>      return &#39;Loading...&#39;;<br>    }</pre><pre>    if(this.state.done) {<br>      return &#39;Done!&#39;;<br>    }</pre><pre>    return &#39;&#39;;<br>  }<br>}</pre><p>Then we can update our template to show the corresponding icon.</p><pre>&lt;h4 v-if=&quot;!state.default&quot; id=&quot;loader&quot; class=&quot;font-light text-blue&quot;&gt;<br>    &lt;i v-show=&quot;state.loading&quot; class=&quot;fas fa-circle-notch fa-spin mr-1&quot;&gt;&lt;/i&gt;<br>    &lt;i v-show=&quot;state.done&quot; class=&quot;far fa-check-circle mr-1&quot;&gt;&lt;/i&gt;<br>    {{ header }}<br>&lt;/h4&gt;</pre><p>As you can see, with this method we’re incredibly explicit about how our template and computed property should react to our state. As I mentioned early, this is the advantage of using the Object method. However, the drawback to this approach is that it can be tedious to update our state.</p><p>Right now, we’d have to reset all of the other states if we wanted to toggle one state. And, imagine if we wanted some parts of our state to be toggled while others should be reset. All of a sudden, this can get pretty tricky because we need to be explicit about what state we’d like to transition to.</p><p>Now, let’s see how the String method compares to the Object method.</p><h3>String Method</h3><p>With the String method, we won’t use an Object to maintain a list of all the possible state combinations. Instead, we’ll just set our state to a String to keep track of the current state.</p><p>Let’s see how to do that with our component. We’ll start by updating our data to us a String.</p><pre>data: {<br>    state: &#39;default&#39;,<br>}</pre><p>With this approach, we can quickly tell the current state of our component. This is tremendously helpful when we’re debugging an issue or testing different permutations of our component.</p><p>Let’s take a closer look at this by finishing our component. Once again, we’ll start by updating our computed property.</p><pre>computed: {<br>  header() {<br>       if(this.state === &#39;loading&#39;) {<br>      return &#39;Loading...&#39;;<br>    }</pre><pre>    if(this.state === &#39;done&#39;) {<br>      return &#39;Done!&#39;;<br>    }</pre><pre>    return &#39;&#39;;<br>  }<br>}</pre><p>And now we can update our template.</p><pre>&lt;h4 v-if=&quot;state !== &#39;default&#39;&quot; id=&quot;loader&quot; class=&quot;font-light text-blue&quot;&gt;<br>    &lt;i v-show=&quot;state === &#39;loading&#39;&quot; class=&quot;fas fa-circle-notch fa-spin mr-1&quot;&gt;&lt;/i&gt;<br>    &lt;i v-show=&quot;state === &#39;done&#39;&quot; class=&quot;far fa-check-circle mr-1&quot;&gt;&lt;/i&gt;<br>    {{ header }}<br>&lt;/h4&gt;</pre><p>As I’m sure you’ve figured out, the String approach has the opposite pros and cons when compared to the Object method. It is excellent at showing the current state of the component, but it’s hard to see all of the possible states.</p><p>This can be alleviated by adding a comment the lists all of the states, but that doesn’t feel like the best solution either. Additionally, using the String method implies that you only have one “active” state to worry about in your component.</p><p>While this may be true for a simple component like our loader, this isn’t always the case. If you think of a form component, we might have to keep track of a submitted and error state independently. This could get be difficult to manage with just one string.</p><h3>The Wrap-Up</h3><p>Both the Object and the String method are viable options for managing our local state. While the Object approach is excellent at giving us a lot of flexibility and visibility into all of the possible states, it can be hard to manage and see what the current state is at any given moment.</p><p>Meanwhile, the String approach presents the opposite set of pros and cons. It is exceptional at showing the current state and very easy to update, but it’s much harder to keep track of all the possible permutations.</p><p>In my projects, my current rule of thumb is to always start with the String method. That way I can quickly iterate through the states my component will need. If I find myself relying on a lot of different states, then I’ll consider refactoring to the Object method or see if I can split my component into smaller pieces.</p><p>As you get comfortable with these approaches, I’m sure you come up with your own flow. Maybe you’ll come up with an even better approach! As always, feel free to ask me any questions on <a href="https://twitter.com/nickjbasile">Twitter</a>. And until next time, happy researching!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5d92fb432" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/managing-local-state-in-vue-js-components-d5d92fb432">Managing Local State In Vue.js Components</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building A “Guide-Driven Blog” Step 2: UX Research]]></title>
            <link>https://nickjbasile.medium.com/building-a-guide-driven-blog-step-2-ux-research-70937da37bbf?source=rss-12d3411267e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/70937da37bbf</guid>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Nick Basile]]></dc:creator>
            <pubDate>Thu, 29 Mar 2018 01:48:53 GMT</pubDate>
            <atom:updated>2018-12-04T15:35:08.545Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*atCl0S5-SPrz55PN2O0TEA.jpeg" /></figure><p>A couple of weeks ago, we <a href="https://nick-basile.com/blog/post/building-a-guide-driven-blog-step-1-planning">came up with a plan</a> to build a “Guide-Driven Blog” together. This week, we’ll start making it a reality by working on our initial User Experience (UX).</p><p>UX is one of those big terms that has a different definition for everyone. For me, it is the systematic process of identifying, researching, and empathizing with our target users’ problems and then solving them via a usable interface.</p><p>Notice how there’s nothing in there about design skills or artistic expression? In my experience, UX is more science than art. And that means we can all do it. In practice, this means that UX is about research, hypotheses, experimentation, and meeting users rather than coming up with incredible designs.</p><p>Don’t get me wrong, if you can do both, then please continue to do so. But, for the rest of us, we can still deliver fantastic user experiences without artistic talent.</p><p>Now that we have a shared understanding of UX let’s walk through how to deliver an excellent experience for our users.</p><h3>Identifying the Problem</h3><p>Fortunately, we’ve already identified our users’ problem in step three of our product plan.</p><blockquote><em>“Readers get to read content that is better formatted for their individual needs.”</em></blockquote><p>Now let’s translate this problem into a testable hypothesis. While articulating a problem is useful, making it into a hypothesis makes it actionable. And that’s what we need to keep moving forward.</p><p>So we hypothesize that “if readers visit a guide-driven blog then they will be able to find relevant content easier than a normal blog because the content is easier to search.”</p><p>This hypothesis is something we can research further.</p><h3>Researching Our Hypothesis</h3><p>Research is always a little tricky. It’s one of those things that everyone loves to pay lip-service to, but very few people do it. It takes time, it’s hard to track down users, and most stakeholders aren’t entirely onboard with it.</p><p>When I present conducting UX research to my colleagues, I often start with the cost of failure. If we spend tons of time and money developing this project and it fails, then we’re going to be in a tough spot.</p><p>But, if we take the time up front to do some research, we increase our chance of building something that is aligned with our users’ needs and thereby increase our chance of success. This approach has worked for me in the past, and I hope you can use it too.</p><p>Since we’re building our own project, we don’t have to worry too much about aligning stakeholders. So, let’s get down to researching. First, we need to recruit some test subjects who closely resemble the end users of our project.</p><h3>Recruiting Test Subjects</h3><p>Recruiting test subject is not an easy feat. If you already have a product, you can reach out to your existing users. But, getting test subjects for a brand new project is hard.</p><p>Hopefully, you’re building something that solves a personal need, and you’ve already talked with some folks about how they’ve experienced it too. These are excellent potential candidates that you can reach out to and try to interview.</p><p>If you don’t know anyone who might fit, I recommend heading to social media and Craigslist to try and drum up some test subjects. If you can’t find anyone there, you might want to reevaluate what you’re building. Because if you can’t reach your target market now, how will you reach them after you’ve spent a lot of time building something?</p><p>Now that we’ve gathered at least five test subjects who closely match our users, we can interview them to see if they’re experiencing the problem we identified. To do that, we’ll need a script.</p><h3>Writing a Script</h3><p>Taking the time to write a script is incredibly essential for two primary reasons. First, it keeps the interview focused, so we don’t waste the interviewee’s time. And second, asking all of the interviewees the same questions keeps our process consistent. If we asked all of them different questions, then our results wouldn’t be beneficial.</p><p>Now coming up with a good script takes a bit of effort, but the rewards are worth it. When I ran my first interview, I didn’t have a good script. I just described the problem and my solution for it and asked the interviewee if that sounded reasonable to them. I didn’t get the insight I was looking for because I didn’t ask my user the right questions.</p><p>Over time, I’ve picked up better questions to ask — especially from <a href="https://twitter.com/ashmaurya">Ash Mayura</a>. My current process is largely based on his, so I highly recommend that you check out <a href="https://blog.leanstack.com/the-updated-problem-interview-script-and-a-new-canvas-1e43ff267a5d">his writings</a> on the subject. With that said, our scripts should essentially break down into three sections.</p><p>The first part is about gleaning some of the interviewee’s demographics like age, gender, job title, industry, etc. These details help us identify patterns and organize patterns we see in their responses. If all the salespeople say one thing and the software engineers say another, then you might have stumbled upon a different problem for each of these groups.</p><p>The second section is about setting the “problem context.” We want to describe the problem to the interviewee in terms they can relate to so they can construct a mental model of the issue and recognize it in their own life. This typically involves telling a story to the interviewee and asking them if they identify with it and what other thoughts it brought to mind.</p><p>This part can generate some vague responses. But, the critical thing to remember is that we’re looking for patterns. If 80% of the interviewees brought up the same pain point or situation, then you’re on to something important and can continue to investigate that in further interviews.</p><p>Finally, we’ll try to figure out how the customer is currently solving their problem in the last section of the interview. Asking them what they do now, if anything, is incredibly illuminating.</p><p>You might find out that they’re solving their problem in a way you would never have thought about. Or, you could learn that they don’t have a great solution and your idea could help them tremendously. This last step can undoubtedly generate some fantastic ideas for you to work on.</p><h3>Validating The Hypothesis</h3><p>Once you have at least five interviews under your belt, you should start to see if folks are resonating with the problem you’re describing or if they don’t care about it. If they’re all asking when your solution will be ready, then your probably on the right track.</p><p>But, if it turns out they don’t care, first, double-check your assumptions that you’ve recruited from the right user group. It could turn out that you presented the right problem to the wrong people.</p><p>If you’re sure you interviewed the right people, focus in on what they did say is a problem. It could be that your original hypothesis is slightly off the mark, but you can pivot to a different problem to solve.</p><p>If it turns out they don’t have anything for you to pivot to, then you can either do another round of interviews to be sure. Or, you can feel confident that you haven’t wasted a bunch of time building something people didn’t want.</p><p>Now that our hypothesis has been validated, it’s time to turn our research into actionable user flows.</p><h3>User Flows</h3><p>Now I know what you’re thinking, “Nick, we already mapped out the user flows in our project plan!” And you’re right, we certainly did. But, now that we’ve done the research, we can revisit these user flows to see how far off our initial assumptions were about our solution.</p><p>Writing out goals and assumptions before testing them is such an important, and frequently forgotten, step in validating an idea. If we don’t have something to compare our results to, then how will we know how right or wrong our initial plans were?</p><p>By comparing our existing user flows to the results we generated from our research, we’re trying to find the intersection of what users are experiencing and our vision for a solution.</p><p>With this in mind, we can revisit our existing flows and check that they’re still relevant. If not, we can update them with the findings from our research.</p><h3>The Wrap-Up</h3><p>While this post, titled “UX,” might seem like something we do at the beginning of a project and then forget about. In reality, it is a never-ending process. As long as we’re building something for other people, we need to be validating our assumptions to ensure that we’re building the right thing.</p><p>Of course, the one big exception to this rule is if you’re making something for yourself. If that’s the case, you could skip these steps and get right to building your idea. Just remember that if you do try and bring it to a broader audience, a little UX research will go a long way towards your success.</p><p>Now that we have our user flows, we can start building our project by putting together some wireframes. As always, feel free to ask me any questions on <a href="https://twitter.com/nickjbasile">Twitter</a>. And until next time, happy researching!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70937da37bbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Write A Plugin For Tailwind CSS]]></title>
            <link>https://nickjbasile.medium.com/how-to-write-a-plugin-for-tailwind-css-898752e3f5e2?source=rss-12d3411267e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/898752e3f5e2</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[package]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Nick Basile]]></dc:creator>
            <pubDate>Fri, 23 Mar 2018 11:47:41 GMT</pubDate>
            <atom:updated>2018-12-04T15:34:56.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YyKCEGPCvGRYHVtdSJDH7Q.jpeg" /></figure><p><a href="https://nick-basile.com/blog/post/5-takeaways-from-using-tailwind-css-in-real-projects">Last week</a>, I covered a few of my top takeaways from using Tailwind CSS in some real projects. I discussed a lot of the positive experiences I had, but I also brought up one of my frustrations with the framework. Namely, the lack of percentage-based height utilities.</p><p>Fortunately for us, Tailwind recently released a plugin system so we can create packages for any functionality that we need! So let’s dive in and see how to create a percentage-based height plugin.</p><h3>The Set Up</h3><p>As usual, we’ll be starting with a fresh Laravel project with Tailwind installed. For a detailed walkthrough on setting that up, you can check out my <a href="https://nick-basile.com/blog/post/how-to-configure-a-new-laravel-55-project">previous post</a>. One caveat is that now we should add @tailwind components to our app.sass file in between our two other @tailwind directives. With everything all set up, we can check out our Tailwind config file and start writing our plugin.</p><h3>Coding Our Plugin</h3><p>At the bottom of our Tailwind config file, we’ll notice that there’s a new Array for plugins that looks like this:</p><pre>plugins: [<br>    require(&#39;tailwindcss/plugins/container&#39;)({<br>      // center: true,<br>      // padding: &#39;1rem&#39;,<br>    }),<br>]</pre><p>Out-of-the-box, the Tailwind team has given us an example plugin to get us started. While they’re importing their container plugin from their package, we can begin writing our plugin by adding a function to the Array.</p><pre>plugins: [<br>    require(&#39;tailwindcss/plugins/container&#39;)({<br>      // center: true,<br>      // padding: &#39;1rem&#39;,<br>    }),<br>    function() {<br>    <br>    }<br>]</pre><p>Anytime we want to add a new plugin; we can just add a new function. Now, according to <a href="https://tailwindcss.com/docs/plugins/">the docs</a>, plugin functions can receive a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">destructured Object</a> containing 5 helper functions.</p><p>These helper functions are addUtilities(), addComponents(), e(), prefix(), and config(). addUtlities() lets us register new utility classes. addComponents is just like addUtilities, but instead of classes we&#39;re registering more complex component classes.</p><p>e() helps us create class names by escaping strings. prefix() lets us manually apply the user-defined Tailwind prefix to our generated classes. And finally, config()lets us access the user&#39;s Tailwind configuration so we can reference their options.</p><p>All of these helpers are super useful, but I bet that we’ll only have to worry about using addUtilities(), addComponents(), and e() for the majority of our plugins.</p><p>For our percentage height plugin, we’ll only be using e() and addUtilities(). So, let&#39;s add that destructured Object to our function.</p><pre>plugins: [<br>    require(&#39;tailwindcss/plugins/container&#39;)({<br>      // center: true,<br>      // padding: &#39;1rem&#39;,<br>    }),<br>    function({e, addUtilities}) {<br>    <br>    }<br>]</pre><p>Great! Before we write our next batch of code, let’s take a moment to think about what we’re trying to do. We are trying to generate a bunch of height classes that follow the existing Tailwind format (.h-1/2) and use the <a href="https://tailwindcss.com/docs/plugins/#css-in-js-syntax">CSS-in-JS</a> syntax to assign their percentage height values. Then, we&#39;ll need to group them all into an Array and pass them through to the addUtilites helper function to register them with Tailwind.</p><p>I think the easiest place to start would be an Array of Objects, where the Object’s properties hold the class name and the height value. So, let’s add that to our function.</p><pre>plugins: [<br>    require(&#39;tailwindcss/plugins/container&#39;)({<br>      // center: true,<br>      // padding: &#39;1rem&#39;,<br>    }),<br>    function({e, addUtilities}) {<br>        let percents = [<br>            {<br>              key: &#39;1/2&#39;,<br>              value: &#39;50%&#39;<br>            },<br>            {<br>              key: &#39;1/3&#39;,<br>              value: &#39;33.33333%&#39;<br>            },<br>            {<br>              key: &#39;2/3&#39;,<br>              value: &#39;66.66667%&#39;<br>            },<br>            {<br>              key: &#39;1/4&#39;,<br>              value: &#39;25%&#39;<br>            },<br>            {<br>              key: &#39;3/4&#39;,<br>              value: &#39;75%&#39;<br>            },<br>            {<br>              key: &#39;1/5&#39;,<br>              value: &#39;20%&#39;<br>            },<br>            {<br>              key: &#39;2/5&#39;,<br>              value: &#39;40%&#39;<br>            },<br>            {<br>              key: &#39;3/5&#39;,<br>              value: &#39;60%&#39;<br>            },<br>            {<br>              key: &#39;4/5&#39;,<br>              value: &#39;80%&#39;<br>            },<br>            {<br>              key: &#39;1/6&#39;,<br>              value: &#39;16.66667%&#39;<br>            },<br>            {<br>              key: &#39;5/6&#39;,<br>              value: &#39;83.33333%&#39;<br>            },<br>            {<br>              key: &#39;1/10&#39;,<br>              value: &#39;10%&#39;<br>            },<br>            {<br>              key: &#39;3/10&#39;,<br>              value: &#39;30%&#39;<br>            },<br>            {<br>              key: &#39;7/10&#39;,<br>              value: &#39;70%&#39;<br>            },<br>            {<br>              key: &#39;9/10&#39;,<br>              value: &#39;90%&#39;<br>            },<br>            {<br>              key: &#39;full&#39;,<br>              value: &#39;100%&#39;<br>            },<br>          ];<br>    }<br>]</pre><p>Alright, now we’re cooking. With our key value data ready, it&#39;ll be pretty easy to use JavaScript&#39;s native .map() functionality to iterate over all of these Objects and generate the Array we need.</p><pre>plugins: [<br>    require(&#39;tailwindcss/plugins/container&#39;)({<br>      // center: true,<br>      // padding: &#39;1rem&#39;,<br>    }),<br>    function({e, addUtilities}) {<br>        let percents = [<br>            {<br>              key: &#39;1/2&#39;,<br>              value: &#39;50%&#39;<br>            },<br>            {<br>              key: &#39;1/3&#39;,<br>              value: &#39;33.33333%&#39;<br>            },<br>            {<br>              key: &#39;2/3&#39;,<br>              value: &#39;66.66667%&#39;<br>            },<br>            {<br>              key: &#39;1/4&#39;,<br>              value: &#39;25%&#39;<br>            },<br>            {<br>              key: &#39;3/4&#39;,<br>              value: &#39;75%&#39;<br>            },<br>            {<br>              key: &#39;1/5&#39;,<br>              value: &#39;20%&#39;<br>            },<br>            {<br>              key: &#39;2/5&#39;,<br>              value: &#39;40%&#39;<br>            },<br>            {<br>              key: &#39;3/5&#39;,<br>              value: &#39;60%&#39;<br>            },<br>            {<br>              key: &#39;4/5&#39;,<br>              value: &#39;80%&#39;<br>            },<br>            {<br>              key: &#39;1/6&#39;,<br>              value: &#39;16.66667%&#39;<br>            },<br>            {<br>              key: &#39;5/6&#39;,<br>              value: &#39;83.33333%&#39;<br>            },<br>            {<br>              key: &#39;1/10&#39;,<br>              value: &#39;10%&#39;<br>            },<br>            {<br>              key: &#39;3/10&#39;,<br>              value: &#39;30%&#39;<br>            },<br>            {<br>              key: &#39;7/10&#39;,<br>              value: &#39;70%&#39;<br>            },<br>            {<br>              key: &#39;9/10&#39;,<br>              value: &#39;90%&#39;<br>            },<br>            {<br>              key: &#39;full&#39;,<br>              value: &#39;100%&#39;<br>            },<br>          ];<br>          <br>          const heightUtilities = percents.map(item =&gt; {<br>            return {<br>              [`.h-${e(item.key)}`]: {<br>                height: item.value<br>              }<br>            }<br>      });<br>    }<br>]</pre><p>Rock on! All we’re doing here is mapping our percents variable to a new constant for heightUtilities. We use an ES6 to pass in the item, and then we generate the CSS we need. Since our class names use special characters, we can use e() and some <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals">String interpolation</a> to parse out a valid class name.</p><p>With our classes ready to go, we can go ahead and register them with addUtilities().</p><pre>plugins: [<br>    require(&#39;tailwindcss/plugins/container&#39;)({<br>      // center: true,<br>      // padding: &#39;1rem&#39;,<br>    }),<br>    function({e, addUtilities}) {<br>        let percents = [<br>            {<br>              key: &#39;1/2&#39;,<br>              value: &#39;50%&#39;<br>            },<br>            {<br>              key: &#39;1/3&#39;,<br>              value: &#39;33.33333%&#39;<br>            },<br>            {<br>              key: &#39;2/3&#39;,<br>              value: &#39;66.66667%&#39;<br>            },<br>            {<br>              key: &#39;1/4&#39;,<br>              value: &#39;25%&#39;<br>            },<br>            {<br>              key: &#39;3/4&#39;,<br>              value: &#39;75%&#39;<br>            },<br>            {<br>              key: &#39;1/5&#39;,<br>              value: &#39;20%&#39;<br>            },<br>            {<br>              key: &#39;2/5&#39;,<br>              value: &#39;40%&#39;<br>            },<br>            {<br>              key: &#39;3/5&#39;,<br>              value: &#39;60%&#39;<br>            },<br>            {<br>              key: &#39;4/5&#39;,<br>              value: &#39;80%&#39;<br>            },<br>            {<br>              key: &#39;1/6&#39;,<br>              value: &#39;16.66667%&#39;<br>            },<br>            {<br>              key: &#39;5/6&#39;,<br>              value: &#39;83.33333%&#39;<br>            },<br>            {<br>              key: &#39;1/10&#39;,<br>              value: &#39;10%&#39;<br>            },<br>            {<br>              key: &#39;3/10&#39;,<br>              value: &#39;30%&#39;<br>            },<br>            {<br>              key: &#39;7/10&#39;,<br>              value: &#39;70%&#39;<br>            },<br>            {<br>              key: &#39;9/10&#39;,<br>              value: &#39;90%&#39;<br>            },<br>            {<br>              key: &#39;full&#39;,<br>              value: &#39;100%&#39;<br>            },<br>          ];<br>          <br>          const heightUtilities = percents.map(item =&gt; {<br>            return {<br>              [`.h-${e(item.key)}`]: {<br>                height: item.value<br>              }<br>            }<br>      });<br>      <br>      addUtilities(heightUtilities, {<br>        variants: [&#39;responsive&#39;],<br>      });<br>    }<br>]</pre><p>Notice that we’ve also included the responsive variant configuration for these classes. addUtilites() <a href="https://tailwindcss.com/docs/plugins/#responsive-and-state-variants">can accept</a> some additional options when we use it. This configuration lets Tailwind take care of generating all of the responsive variations for us.</p><p>If we run our build process now, we can see that our new height utilities are available for us to use!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fI1JOY5mSUli9Ydd.png" /></figure><h3>Extracting to an NPM Package</h3><p>While this is super awesome to have in our project, it’s annoying to have to copy this every time we want to add these classes. Instead, we can extract this to an NPM package and just include it in our projects!</p><p>To start, we can create a new directory with an index.js file inside of it. Inside of index.js, we&#39;ll add a module.exports so our package users can import our functionality.</p><pre>module.exports = function () {</pre><pre>}</pre><p>Now, we can simply copy and paste our plugin into our export.</p><pre>module.exports = function () {<br>    function({e, addUtilities}) {<br>        let percents = [<br>            {<br>              key: &#39;1/2&#39;,<br>              value: &#39;50%&#39;<br>            },<br>            {<br>              key: &#39;1/3&#39;,<br>              value: &#39;33.33333%&#39;<br>            },<br>            {<br>              key: &#39;2/3&#39;,<br>              value: &#39;66.66667%&#39;<br>            },<br>            {<br>              key: &#39;1/4&#39;,<br>              value: &#39;25%&#39;<br>            },<br>            {<br>              key: &#39;3/4&#39;,<br>              value: &#39;75%&#39;<br>            },<br>            {<br>              key: &#39;1/5&#39;,<br>              value: &#39;20%&#39;<br>            },<br>            {<br>              key: &#39;2/5&#39;,<br>              value: &#39;40%&#39;<br>            },<br>            {<br>              key: &#39;3/5&#39;,<br>              value: &#39;60%&#39;<br>            },<br>            {<br>              key: &#39;4/5&#39;,<br>              value: &#39;80%&#39;<br>            },<br>            {<br>              key: &#39;1/6&#39;,<br>              value: &#39;16.66667%&#39;<br>            },<br>            {<br>              key: &#39;5/6&#39;,<br>              value: &#39;83.33333%&#39;<br>            },<br>            {<br>              key: &#39;1/10&#39;,<br>              value: &#39;10%&#39;<br>            },<br>            {<br>              key: &#39;3/10&#39;,<br>              value: &#39;30%&#39;<br>            },<br>            {<br>              key: &#39;7/10&#39;,<br>              value: &#39;70%&#39;<br>            },<br>            {<br>              key: &#39;9/10&#39;,<br>              value: &#39;90%&#39;<br>            },<br>            {<br>              key: &#39;full&#39;,<br>              value: &#39;100%&#39;<br>            },<br>          ];<br>          <br>          const heightUtilities = percents.map(item =&gt; {<br>            return {<br>              [`.h-${e(item.key)}`]: {<br>                height: item.value<br>              }<br>            }<br>      });<br>      <br>      addUtilities(heightUtilities, {<br>        variants: [&#39;responsive&#39;],<br>      });<br>    }<br>}</pre><p>Who knew writing an NPM package could be so easy? Now to get it up on npmjs.com, we can jump into our CLI.</p><p>Inside of our package directory, we can run npm init to create a package.jsonfile. It&#39;s pretty easy just to follow the prompts. The only one that tripped me up was the tests one. But, I just left it blank, and everything worked fine.</p><p>Just like that our package is ready to be published on NPM. To start, we’ll need to create a user account, if you don’t already have one, by running npm adduser. Next, we&#39;ll need to double check that the name we&#39;d like to use isn&#39;t already taken by doing a quick search on <a href="https://www.npmjs.com/">npmjs.com</a>.</p><p>Once we’re all set, we can just run npm publish and now we can see our package at https://npmjs.com/package/&lt;package&gt;. Bada bing bada boom, we have ourselves an NPM package.</p><blockquote><em>You don’t have to worry about publishing the height plugin as a package, because you can already find it </em><a href="https://github.com/nickbasile/tailwind-percentage-heights-plugin"><em>here</em></a><em>.</em></blockquote><h3>The Wrap-Up</h3><p>Tailwind has made leaps and bounds since its release, and with the addition of plugins we can finally encapsulate and share all of the wonderful utilities and components we’ve been working on. I hope you feel confident to go out and add your own plugins to the ecosystem, and be sure to share them with me! As always, feel free to ask me any questions on <a href="https://twitter.com/nickjbasile">Twitter</a>. And until next time, happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=898752e3f5e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>