<?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 Warrick Bayman on Medium]]></title>
        <description><![CDATA[Stories by Warrick Bayman on Medium]]></description>
        <link>https://medium.com/@warrickbayman?source=rss-b9992064b5fc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WQySNjP8v4MvW24-.png</url>
            <title>Stories by Warrick Bayman on Medium</title>
            <link>https://medium.com/@warrickbayman?source=rss-b9992064b5fc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 15:49:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@warrickbayman/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Laravel Eloquent relationships have a bunch of “with” methods you might not know about.]]></title>
            <link>https://warrickbayman.medium.com/laravel-eloquent-relationships-have-a-bunch-of-with-methods-you-might-not-know-about-eb94f6df151b?source=rss-b9992064b5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb94f6df151b</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[eloquent]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Warrick Bayman]]></dc:creator>
            <pubDate>Thu, 17 Feb 2022 19:01:10 GMT</pubDate>
            <atom:updated>2022-02-23T18:56:13.097Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CETkS-VHDSMKe7hm" /><figcaption>Photo by <a href="https://unsplash.com/@joshuaearle?utm_source=medium&amp;utm_medium=referral">Joshua Earle</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>This post was was originally published on <a href="https://thepublicgood.dev/">THEPUBLICGOOD</a> blog. You can find it <a href="https://blog.thepublicgood.dev/laravel-eloquent-has-a-bunch-of-with-methods-you-might-not-know/">here</a>.</blockquote><p>Eloquent is the database ORM that is included with Laravel. Taylor Otwell recently stated that it’s one of the most complex pieces of Laravel to maintain. Yet it’s probably one of the most important reasons why Laravel has become so super popular.</p><p>You may already have a good handle of how Eloquent works and there’s a bunch of useful tools that are included. One those tools you might already know about is the withCount method. This is really handy if you need to include a count of a related model. Let’s say you have a User and Post model and want to include the number of posts per user when making a query. You would probably have your User model set up with a posts() method like this:</p><pre>public function posts(): HasMany<br>{<br>    return $this-&gt;hasMany(Post::class);<br>}</pre><p>Your Eloquent query would then look something like this:</p><pre>$users = User::withCount(&#39;posts&#39;)-&gt;get();</pre><p>Eloquent will automatically build up the queries for you so that you get the number of posts per user included in the resulting model instance, which you can get to like this:</p><pre>$posts = $users-&gt;first()-&gt;posts_count;</pre><p>But did you know that there are a few more than just withCount?</p><h3>withMax and withMin</h3><p>withMax and withMin methods can be used to get the maximum or minimum value of an attribute on the related model. Using the example from above, let&#39;s say posts have a rating. You might want to know what the highest, or the lowest rating is across all the users posts.</p><pre>// Get the highest rating<br>$max = User::withMax(&#39;posts&#39;, &#39;rating&#39;)-&gt;get();<br><br>// Or the lowest rating<br>$min = User::withMin(&#39;posts&#39;, &#39;rating&#39;)-&gt;get();</pre><p>Eloquent will include a posts_max_rating or a posts_min_rating on the User model instance. You can even rename the attribute if you want by using the “as” syntax like this:</p><pre>$max = User::withMax(‘posts as max_rating’, ‘rating’)-&gt;get();</pre><h3>withSum</h3><p>Similarly, you can use the withSum method to get the total value of all the ratings added together.</p><pre>$total = User::withSum(&#39;posts as total_rating&#39;, &#39;rating&#39;)-&gt;get();</pre><p>You’d get a posts_sum_rating attribute on each User instance.</p><h3>withAvg</h3><p>The withAvg method is really handy if you need to know what the average rating is across multiple relations. For a recent project we needed to know what the rating was of a list of contacts. Each contact was giving a health rating out of 100 and we wanted to give the list a rating as well based on the health of each contact. We can get the average rating across all the contacts on the list in one query using the withAvg method:</p><pre>$contacts = ContactList::orderBy(&#39;title&#39;)<br>    -&gt;withAvg(&#39;contacts as rating&#39;, &#39;rating&#39;)<br>    -&gt;get();</pre><p>This gives us a rating attribute on every ContactList model instance. We didn’t need to do any math in our code. The database did the heavy lifting for us and we got the results we needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb94f6df151b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel model presenters with the Reflection API]]></title>
            <link>https://warrickbayman.medium.com/laravel-model-presenters-with-the-reflection-api-9ebd4e19489f?source=rss-b9992064b5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ebd4e19489f</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[reflection-api]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Warrick Bayman]]></dc:creator>
            <pubDate>Tue, 08 Feb 2022 08:28:34 GMT</pubDate>
            <atom:updated>2022-02-11T07:07:49.581Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Reflection" src="https://cdn-images-1.medium.com/max/1024/0*KVO7wWy5sopDRC9V" /><figcaption>Photo by <a href="https://unsplash.com/@peperg?utm_source=medium&amp;utm_medium=referral">Pepe Reyes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>I’ve spent a number of years writing on Medium, and I’ve really enjoyed the experience. However, after waiting forever for Medium to provide some better tools for writing these sorts of technical articles, I’ve realised that it’s probably not going to happen. Therefore, I’ve decided to move some of my content to my own blog platform where I have more control. Since I also run a small dev company, it made sense to me to create a company blog instead.</blockquote><blockquote>I still love Medium and I’ll continue to publish here for the foreseeable future, but it won’t be everything. I’m trying to force myself to write more these days, so there will likely be more content there and only some stuff on Medium.</blockquote><blockquote>If you’re interested in supporting me, then please take a look at <a href="https://blog.thepublicgood.dev/">https://blog.thepublicgood.dev/</a>. There’s no charge, I promise. It’s still early days and I’m still working things out, but I like where I’m going with this.</blockquote><blockquote>If you want to read this article on the blog instead, you can find it here: <a href="https://blog.thepublicgood.dev/using-reflection-api-to-create-laravel-model-presenters/">https://blog.thepublicgood.dev/using-reflection-api-to-create-laravel-model-presenters/</a>.</blockquote><blockquote>Thanks for reading my stuff.</blockquote><p>There are many instances where I’ve needed to format data stored in a model so it can be presented in a view somehow. In the passed I’ve approached this particular problem in a few different ways, and yes, I could easily format that data directly in the view, but that quickly becomes a chore and then it tends to become a bit repetitive. It’s also a place for errors or inconsistencies to creep in. Things like this can become common, and they’re nasty:</p><pre>{{ $article-&gt;created_at-&gt;format(&#39;d F Y H:i a&#39;) }}</pre><p>I wanted a solution that I could use over and over again that would provide an easy way to present model data in an elegant way. I started with just creating basic accessor methods on the model class:</p><pre>public function getPresentableCreatedAtAttribute(): string<br>{<br>    return $this-&gt;created_at-&gt;format(&#39;d F Y H:i a&#39;);<br>}</pre><p>This can then be used in a view whenever I need it:</p><pre>{{ $article-&gt;presentable_created_at }}</pre><p>This actually worked really well. Maybe I have the wrong term here, but I like to call them model presenters. Laravel already provides everything we need to make this work. You can even make it reusable by putting that method in a trait and using it in each model where needed. If this works for you, then read no further.</p><pre>// app\Http\Presenters\ArticlePresenter.php<br><br>namespace App\Http\Presenters;<br><br>trait ArticlePresenter<br>{<br>    public function getPresentableCreatedAtAttribute(): string<br>    {<br>        return $this-&gt;created_at-&gt;format(&#39;d F Y H:i a&#39;);<br>    }<br>}</pre><p>But if you’re like me and you like to figure out alternate solutions to things like this, then you’ll understand why I wrote <a href="https://github.com/tpg/is-presentable">a small package that does this for me</a>. It’s called IsPresentable. The first version really just built a little on the idea of the accessor method. Simply adding the IsPresentable trait to a model gave you thr abilty to create create presentable methods like this:</p><pre>public function presentableCreatedAt(): string<br>{<br>    return $this-&gt;created_at-&gt;format(&#39;d F Y H:i a&#39;);<br>}</pre><p>Then, in a Blade view, it could be used like this:</p><pre>{{ $article-&gt;presentable()-&gt;created_at }}</pre><p>Again, putting these presentable methods in a trait made them portable. I could simply add the trait to any model I needed the presentable methods in.</p><p>Since that first version, the package has grown up a little and now adds a bunch of new features, like presentable classes.</p><p>IsPresentable also overrides the toArray method on the model so when it get cast to an array or a JSON string, presenters are included automatically. This means it can be used in a JavaScript front-end like this:</p><pre>article.presentable.created_at;</pre><p>There’s a few other features that make IsPresentable special, but at it’s heart is the PHP reflection API.</p><h3>What is the Reflection API?</h3><p>PHP’s Reflection API allows us to inspect our code at runtime. For example, the IsPresentable package needs to get a list of methods from the current class whose names begin with the word presentable. The Reflection API gives us that ability without needing to ask the user to explicitly state the method names.</p><h3>A simple example</h3><p>Using a Laravel model as as example, let’s get all the methods that start with the word presentable and return a Laravel collection. To help make this reusable we&#39;ll create a new trait called IsPresentable. Create a new trait at app/Http/Presenters/IsPresentable.php and add a protected method named getPresentableMethods:</p><pre>namespace App\Http\Presenters;<br><br>use Illuminate\Support\Collection;<br><br>trait IsPresentable<br>{<br>    protected function getPresentableMethods(): Collection<br>    {<br>        //...<br>    }<br>}</pre><p>This method needs to get all the methods that start with presentable and return their a collection of names. The simplest start to the Reflection API is passing the current class to a new instance of ReflectionClass. This will give us a bunch of information about the current class including all its methods:</p><pre>&lt;?php</pre><pre>namespace App\Http\Presenters;</pre><pre>use Illuminate\Support\Collection;<br>use ReflectionClass;</pre><pre>trait IsPresentable<br>{<br>    protected function getPresentableMethods(): Collection<br>    {<br>        $reflection = new ReflectionClass($this);<br>        $methods = $reflection-&gt;getMethods();<br>    }<br>}</pre><p>Obviously, we don’t want all the methods, so we can create a new collection and use the filter method to get only the methods we want:</p><pre>&lt;?php</pre><pre>namespace App\Http\Presenters;</pre><pre>use Illuminate\Support\Collection;<br>use Illuminate\Support\Str;<br>use ReflectionClass;<br>use ReflectionMethod;</pre><pre>trait IsPresentable<br>{<br>    protected function getPresentableMethods(): Collection<br>    {<br>        $reflection = new ReflectionClass($this);<br>        <br>        $methods = collect($reflection-&gt;getMethods())<br>            -&gt;filter(fn (ReflectionMethod $method) =&gt; Str::startsWith($method-&gt;name, &#39;presentable&#39;));<br>    }<br>}</pre><p>Now we can use map to get the names of the methods and return the resulting collection:</p><pre>&lt;?php</pre><pre>namespace App\Http\Presenters;</pre><pre>use Illuminate\Support\Collection;<br>use Illuminate\Support\Str;<br>use ReflectionClass;<br>use ReflectionMethod;</pre><pre>trait IsPresentable<br>{<br>    protected function getPresentableMethods(): Collection<br>    {<br>        $reflection = new ReflectionClass($this);<br>        <br>        $methods = collect($reflection-&gt;getMethods())<br>            -&gt;filter(fn (ReflectionMethod $method) =&gt; Str::startsWith($method-&gt;name, &#39;presentable&#39;));</pre><pre>return $methods-&gt;map(fn (ReflectionMethod $method) =&gt; $method-&gt;name);<br>    }<br>}</pre><p>Cool. Now we have a collection of method names that all start with the word presentable. Let&#39;s add another method called getPresentables which will return a snake-cased version of the method names and their return values as an array:</p><pre>protected function getPresentables(): array<br>{<br>    return $this-&gt;getPresentableMethods()-&gt;mapWithKeys(function (string $methodName) {<br>        return [Str::snake(Str::after($methodName, &#39;presentable&#39;)) =&gt; $this-&gt;$methodName()];<br>    })-&gt;toArray();<br>}</pre><p>The mapWithKeys method on the collection let&#39;s us specify the resulting key and the value. The Str::after($methodName, &#39;presentable&#39;) bit will remove the presentable word from the method name and Str::snake(...) will give us the snake case version of the remaining method name.</p><p>So if I have method named presentableCreatedAt which returns a date string, I&#39;d end up with the following in my array:</p><pre>[<br>    &#39;created_at&#39; =&gt; &#39;2022-02-11 16:45:31&#39;,<br>]</pre><p>Great! How do I use it? I think it would be cool to have something like this now:</p><pre>$user-&gt;present()-&gt;created_at;</pre><blockquote>The IsPresentable package uses presentable() instead of present(). You can do the same here if you wish, but remember that our getPresentableMethodsreturn ALL methods that start with presentable which would return this method as well.</blockquote><p>To get this right, we’ll need another class which we’ll call Presenter. We&#39;ll pass the array we get from getPresentables(). The Presenter class doesn&#39;t need to be very complex. Create a new file at app/Http/Presenters/Presenter.php:</p><pre>&lt;?php</pre><pre>namespace App\Http\Presenters;</pre><pre>class Presenter<br>{<br>    public function __construct(protected array $presentables = [])<br>    {}</pre><pre>    public function __get($name): mixed<br>    {<br>        return Arr::get($this-&gt;presentables, $name);<br>    }<br>}</pre><p>This class will simply accept the array of presentable keys and values. The magic __get() method will return the value of the of the given key.</p><p>Lastly, let’s update the IsPresentable trait with a present() method:</p><pre>&lt;?php</pre><pre>namespace App\Traits;</pre><pre>use Illuminate\Support\Collection;<br>use Illuminate\Support\Str;<br>use App\Presenter;<br>use ReflectionClass;<br>use ReflectionMethod;</pre><pre>trait IsPresentable<br>{<br>    public function present(): Presenter<br>    {<br>        return new Presenter($this-&gt;getPresentables());<br>    }</pre><pre>protected function getPresentables(): array<br>    {<br>        return $this-&gt;getPresentableMethods()-&gt;mapWithKeys(function (string $methodName) {<br>            return [Str::snake(Str::after($methodName, &#39;presentable&#39;)) =&gt; $this-&gt;$methodName()];<br>        })-&gt;toArray();<br>    }</pre><pre>protected function getPresentableMethods(): Collection<br>    {<br>        $reflection = new ReflectionClass($this);<br>        <br>        $methods = collect($reflection-&gt;getMethods())<br>            -&gt;filter(fn (ReflectionMethod $method) =&gt; Str::startsWith($method-&gt;name, &#39;presentable&#39;));</pre><pre>return $methods-&gt;map(fn (ReflectionMethod $method) =&gt; $method-&gt;name);<br>    }<br>}</pre><p>So now we can add the IsPresentable trait to any model and create new presentable methods by prefixing them with the word presentable. For example, say you wanted to format the created_at property on the User model, we can now do this:</p><pre>namespace App\Models;<br><br>use App\Http\Presenters\IsPresentable;<br>use Illuminate\Foundation\Auth\User as Authenticatable;<br><br>class User extends Authenticatable<br>{<br>    use IsPresentable;<br>    <br>    protected function presentableCreatedAt(): string<br>    {<br>        return $this-&gt;created_at-&gt;format(&#39;d F Y H:i a&#39;);<br>    }<br>}</pre><p>And you can output it like this:</p><pre>$user-&gt;present()-&gt;created_at;</pre><p>There’s a lot we can do with the Reflection API and this is a really simple example. Our <a href="https://github.com/tpg/is-presentable">IsPresentable</a> package is able to do a lot more and is quite flexible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ebd4e19489f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel, Vue and Inertia with Vite]]></title>
            <link>https://warrickbayman.medium.com/laravel-vue-and-inertia-with-vite-4b8b825b790a?source=rss-b9992064b5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b8b825b790a</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[inertia]]></category>
            <category><![CDATA[vitejs]]></category>
            <dc:creator><![CDATA[Warrick Bayman]]></dc:creator>
            <pubDate>Fri, 22 Oct 2021 13:38:13 GMT</pubDate>
            <atom:updated>2023-06-23T06:33:48.367Z</atom:updated>
            <content:encoded><![CDATA[<h4>Webpack is great… but there might be better.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*17dT8ifFaFyG87xoBQoIxg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@benwhitephotography?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ben White</a> on <a href="https://unsplash.com/s/photos/strong?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote>I wrote this some time ago. Since then Laravel hass come out with first-party Vite support. If you’re starting a new Laravel project today, you don’t need this article. It’s still here if you really want to read it, but you don’t actually need it.</blockquote><h4>But first… some shameless self promotion</h4><p>Vite is a fantastic piece of software and if you’re keen to see how I got it working with Laravel and Inertia, then read on. However, if you just want it to work, then I’ve written a simple Laravel package that will “boiletplate” this all out for you. It’s called “Vitamin” (clever, I know). I’ve managed to work out how to get around a lot of the stumbling blocks so it’s a fairly safe solution to all this, and will get you there in just a few minutes. Check it out <a href="https://github.com/tpg/vitamin">here</a>.</p><h4>Also, a shout out</h4><p>When I started experimenting with Vite, <a href="https://sebastiandedeyne.com/vite-with-laravel/">This article</a> by Sebastian De Deyne got me 90% of the way. There were a few things that didn’t work for me and I had to figured out a bunch, but you may notice some similarities. There’s also a <a href="https://laravel-vite.innocenzi.dev/">laravel-vite</a> package that’s worth looking at.</p><p>Vite is still quite new and there’s isn’t too much documentation or tooling around its use with Laravel out there. But it’s a great tool and it works really well with things I already use. Here’s hoping you find this post useful as well.</p><h3>Into the fray…</h3><p>I’m a big Laravel fan. Not only has it helped me become a better programmer, but it’s now also a central component of my own business. I can’t really see myself giving up Laravel any time in the near future.</p><p>Laravel comes with its own templating language called Blade. Blade is great and I’ve built many a project with it. At some point I also started using Vue to sprinkle a little interactive magic into those blade files. It’s a nice way to go, but I felt like there were other solutions. Don’t get me wrong, Blade is great and I still use it plenty, I was just interested in learning something new.</p><p>Over the years I’ve also built a few single-page apps using Laravel and Vue, but I’ve never really been a big fan of that path. Vue-router and Vuex are really great tools, but making it all work with Laravel just felt awkward. So when Johnathan Reinink wrote his first blog post on what would eventually become Inertia, I was hooked.</p><p>At the time, I worked for a small web developement company, and as lead developer I had a lot of sway over our tech choices, so being the tech bully I can sometimes be, I managed to get us to buld a single project using the ideas that Johnathan spoke about. It was like a breath of fresh air. We got all the magic of Laravel but could build our front-end completely in Vue single-file components. When Inertia was eventually released it was a no-brainer. It made perfect sense for me.</p><p>So over the last little while, my tech stack has been almost exclusively Laravel, Vue, and Inertia. This all works because Webpack and Laravel Mix are great. There’s also not really a lot of initial set up needed. Laravel even comes with a “one-click install” for this setup these days.</p><p>However, There’s a big shortfall here: It’s slow. It works wonders when your project is small and has a fairly simple UI, but as soon as it starts getting a bit more complex, things slow down. This is because each time you make a change, your entire front-end gets re-bundled. This means that you could end up waiting upto 15 seconds each time you make a change, and that’s just not cool.</p><p>I figured I needed some way to speed things up. As a big Vue fan, I’d already heard about Vite, but didn’t really give it much thought at the time because I was happy with my set up. I didn’t think I needed to change anything. Well, after getting frustrated while working on a very large front-end project, I decided it was time to take another look. The speed improvement is insane. My productivity has improved tenfold. I spend zero time waiting for things to bundle and my old 2017 Macbook CPU is really grateful. I don’t hear that aweful fan nearly as much now.</p><p>Vite is fast because it leverages a fairly modern browser feature called ES modules. All modern browsers support modules now so your front-end components get injected into the browser each time you make a change. No need to bundle all your components together, so no waiting. Changes are close to instant.</p><p>Setting up Vite with Laravel takes a little work, but it really is worth the effort. There’s a few articles out there that describe getting Laravel and Vite working, and the best one I found was from Sebastian De Deyne (link above).</p><p>I’ve been building on Sebastian’s idea and I think I now have a Vite based build pipeline that suites me well. So this article will describe the initial setup and some of the pitfalls I almost got caught up in.</p><h4>Before you begin</h4><p>It’s important to note that this is fairly opinionated. It works well for me, but there are some caveats. It’s up to you what you’re willing to put up with and remember Webpack has been around a lot longer than Vite. If you’re uncomfortable using newer tools, then this might not be for you.</p><p>I’ve also found that some changes don’t get inserted into the browser automatically. making changes to your template in a Vue component works fine, but adding a child component, or making changes to any scripts require a browser reload. This is because of how Vue components are booted. I don’t mind reloading my browser every so often.</p><h4>First steps</h4><p>This is a Laravel approach to Vite, so obviously you’ll need a Laravel app. I’ve had success moving an older Laravel Mix app over, so you can do it on something that already exists, but to make these first attempts easier I’d suggest starting with a fresh app. It’s also important to note that I’m a Laravel Valet user and I wanted to continue using that.</p><p>Once you have a new Laravel app up and running and you can get to it through your browser, you’re ready to go.</p><p>First, you can remove all the bits you don’t need anymore. You’re not using Webpack or Laravel Mix anymore, so you can remove any associated files. You can also remove some of the default Laravel stuff:</p><pre>webpack.mix.js<br>resources/views/welcome.blade.php</pre><p>You’ll also want to remove the Laravel Mix dependency from package.json.</p><p>Next, you’ll need to install dependencies for Inertia, Vite, Vue and Tailwind. (You don’t need to use Tailwind if that’s not your thing, but it’s my go-to now days, so I’ve included it here). The only PHP dependency you’ll need forr now is Inertia, so:</p><pre>composer require inertiajs/inertia-laravel</pre><p>Then the Node dependencies for Inertia, Vue, Vite and Tailwind:</p><pre>yarn add <a href="http://twitter.com/inertiajs/inertia">@inertiajs/inertia</a> <a href="http://twitter.com/inertiajs/inertia-vue3">@inertiajs/inertia-vue3</a> vue@next vite <a href="http://twitter.com/vitejs/plugin-vue">@vitejs/plugin-vue</a> <a href="http://twitter.com/vue/compiler-sfc">@vue/compiler-sfc</a> autoprefixer@latest postcss@latest tailwindcss@latest --dev</pre><p>Now let’s get the Tailwind, Inertia and Vue configuration bits out of the way. Tailwind is fairly simple:</p><pre>npx tailwindcss init -p</pre><p>In your resources/css/app.css add:</p><pre><a href="http://twitter.com/tailwind">@tailwind</a> bade;<br><a href="http://twitter.com/tailwind">@tailwind</a> components;<br><a href="http://twitter.com/tailwind">@tailwind</a> utilities;</pre><p>In the newly created tailwind.config.js change the purge array to:</p><pre>purge: [<br>    &#39;./resources/js/**/*.{vue,js}&#39;,<br>    &#39;./resources/views/**/*.blade.php&#39;<br>],</pre><p>I’d also recommend adding mode: &#39;jit&#39;, to that config.</p><p>Next is Vue and Inertia, and it’s easy to start with the defaults found in the Inertia documentation. When dealing with larger apps, it can be really handy to split your JavaScript up into separate files so that each file is much smaller than using one large bundle. These separate files can then be dynamically imported into the application only when they’re needed. Vite supports dynamic imports by default, but you’ll need to make a change first.</p><p>You can’t use the require method anymore because that’s a Webpack implementation. Instead, you need to use import. You can then use the import.meta.glob method to only import the pages we want to split. The standard async-await JavaScript feature comes in handy here to pass a function to theresolve on createInertiaApp.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a09ace7cfe22a86e6e666bd8c29103f/href">https://medium.com/media/0a09ace7cfe22a86e6e666bd8c29103f/href</a></iframe><blockquote>If you’re just starting out with Inertia, one of the things you’ll miss is Laravel’s super handy `route` helper function. If that sounds like you then I cannot recommend <a href="https://github.com/tightenco/ziggy">Ziggy</a> highly enough. It takes all your Laravel routes and makes them available to your front end. It then gives you a similar `route` helper function. I use it in nearly every Laravel project.</blockquote><h4>Vite Configuration</h4><p>Vite is configured using a vite.config.js file placed at the root of your project. TypeScript is supported out of the box, so you could name the file vite.config.ts. I’ve only recently started with TypeScript and still deciding if it’s all worth it. I’m not going that route for now, but if I feel more confident in the future then I’ll update this with some info. If you’re a TypeScript pro, then I’m sure you’ll manage to make the necessary changes.</p><p>Before you get to configuration, it’s important to know that Vite will still bundle your JavaScript for production. There are some details about this <a href="https://vitejs.dev/guide/why.html#why-bundle-for-production">here</a>. Vite does requires a slightly different mindset if you’re used to how Laravel Mix works, but it’s easy to understand once you know why. During development, Vite actually spins up a web server to serve your assets. Remember that there’s no bundling, so your browser needs to know how to get hold of them. This is the bit that makes Vite magical. But it does mean that there’s a few extra steps to setting it up.</p><p>Setting up Vite is fairly simple. If you have any experience configuring Webpack, this will seem like a breath of fresh air. Here’s a basic vite.config.js configuration file to start with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d99de1d50c291b4ac2fe89c9765e0bd/href">https://medium.com/media/0d99de1d50c291b4ac2fe89c9765e0bd/href</a></iframe><p>Vite will inject the command that is run into the config file so you can use that information to change the configuration depending on the environment you’re currently working in. This is really handy. The command parameter will be either serve or build depending on how you run vite from the command-line, which would normally look something like this:</p><pre>npx vite build</pre><pre>// or</pre><pre>npx vite serve</pre><p>You’ll use this command parameter soon.</p><p>By default, Vite assumes that the base directory is the public path your assets are served from. You might be used to having a js and css directory, but I’d suggest using a single build directory for all your assets. Doing so makes it easier to configure and it’s easier to just ignore a whole directory when you eventually commit this to your repo. You can tell Vite to do this by setting the base config option:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c2263656c57f54dcbb54e0100ae4e35/href">https://medium.com/media/2c2263656c57f54dcbb54e0100ae4e35/href</a></iframe><p>The catch here is that this is only for production. During development, you don’t need this base directory because Vite will serve your unbundled assets through its own server. This is where that command parameter comes into play:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0a13ffaa33a0e36afef7a74b6c20850/href">https://medium.com/media/b0a13ffaa33a0e36afef7a74b6c20850/href</a></iframe><p>Now when you run Vite in development, it will spin up a web server to serve development assets and wont use the build path. But when bundling for production, the build path will be used when generating a manifest (we’ll get to this soon).</p><p>The next setting we need to look at is publicDir. As the Vite documentation states, this is the directory that Vite will serve at / during dev. When building for production, assets in this directory will be copied to outDir (which we’ll get to next). Since we already have a public directory, we don’t really need Vite to copy anything, so we can set this to false:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a89aca021960aa3e3638cef14f2f072a/href">https://medium.com/media/a89aca021960aa3e3638cef14f2f072a/href</a></iframe><p>That’s it for the development config, now we just need to add some stuff for when you run build. Vite’s build config is all under the build key and there’s a few things you’ll want to set here. If you’re familiar with Laravel Mix, then you’ll know what the mix-manifest.json file is for. You can get Vite to do the same thing by setting `manifest` to `true`:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a10893f852e92e146d7e7114c01f7fc3/href">https://medium.com/media/a10893f852e92e146d7e7114c01f7fc3/href</a></iframe><p>We also need to tell Vite where to place the bundled assets. We can do so using the `outDir` option:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93e3bfef6f10df46e9781e4ed337926b/href">https://medium.com/media/93e3bfef6f10df46e9781e4ed337926b/href</a></iframe><p>So now you’ve told Vite that the base path for all assets is /build/ which will be used when you bundle assets for production. So if your app will eventually be at <a href="https://my.app/">https://my.app</a> then <a href="https://my.app/build">https://my.app/build</a> will be where you’ll find all the bundled assets. You’ve also told it that when building for production, to place everything in the public/build directory.</p><p>The last thing you need to do is specify where the main JavaScript file is. Vite uses Rollup in the same way that Laravel Mix uses Webpack. You can get Vite to pass all sorts of stuff to Rollup, but the only thing you need to worry about right now is the entry point. You can set this using the input Rollup config option and passing it to rollupOptions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9dd52e319a7fc5ff0d9a26606f998f0/href">https://medium.com/media/c9dd52e319a7fc5ff0d9a26606f998f0/href</a></iframe><p>That’s a good start. If you run npx vite serve now, you’ll get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*v8fEAcZ8ofHK5jPVCxoePQ.png" /><figcaption>Running vite dev server</figcaption></figure><p>You should now have a dev server running at <a href="https://localhost:3000/">https://localhost:3000/</a>. If you run npx vite build, Vite will bundle your assets ands you should get a public/build directory with your bundled assets. Remember that Vite doesn’t know anything about your Laravel app, and it shouldn’t. It’s only concerned with serving and bundling front-end assets.</p><h4>Valet</h4><p>I like Valet. I work on a bunch of different projects on a daily bais, so Valet makes that a little simpler. There might be better solutions here, but Valet feels natural to me. To make this work with Valet, you need to tell Vite what host you’re using otherwise you’ll come up agaist a whole bunch of CORS errors.</p><p>You can do this by adding a --host option when running Vite:</p><pre>npx vite serve --host=mysite.test</pre><p>Working this way leads to a small problem. Using the FontSource library, I found that Vite would not be able to find the font files when running in dev. Production builds were fine, but it kept getting the path wrong in dev. I managed to solve this by using a custom Valet driver. If you’re not sure what I mean, Valet uses drivers to help serve applications built with different frameworks. And there is a default Laravel driver that we can extend. Create a new PHP file at your project root called LocalValetDriver.php and add the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d60fa99bfd1cb255a1c8451de99b18b/href">https://medium.com/media/8d60fa99bfd1cb255a1c8451de99b18b/href</a></iframe><p>That should do it. Valet will now use this driver instead of the default Laravel one. I found this to be a quick, simple solution to solving the FontSource issue and it should fix any other libraries with similar isues. All this is really doing is checking if the string node_modules is in the requested URI and telling Valet that it’s not a static file and it can serve the url.</p><h4>Scripts</h4><p>Since you’ll be running serve and build a bunch, you can add those as scripts to our package.json file. Remove all the scripts that are there by default (these are for Laravel Mix which we’re not using anymore) and replace with two new ones:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a37ce282532decf2a7829c64bb760868/href">https://medium.com/media/a37ce282532decf2a7829c64bb760868/href</a></iframe><p>Now when you want to start the dev server, you can just do:</p><pre>yarn dev</pre><p>Or if you’re ready to build for production:</p><pre>yarn prod</pre><p>Since everything now goes into a build directory, it’s easy to add to your .gitignore file. You shouldn’t be commiting that stuff to your repo.</p><h4>Laravel and Inertia</h4><p>If you’re a Laravel Mix person, then one thing that may seem confusing is that assets are now served from two different locations. In development, your assets are served from the resources directory by Vites development server without being bundled. For production, your assets are served from public/build. You may have guessed that this could be a bit of a challenge from a Laravel point of view. However, we have all the tools we need to make this work.</p><p>Inertia assumes that your base view file is resources/views/app.blade.php. In this view you’ll need to check when it’s appropriate to load assets from the different locations. In production you can use the contents of the build/manifest.json file to load the bundled assets, while Vite will take care of assets during development. You can make use of the @production Blade directive to only target stuff that is meant for production. This means that we can change where assets are loaded from simply by changing the value of APP_ENV:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54a118b95a2bbf41807cd2b4ce13c65e/href">https://medium.com/media/54a118b95a2bbf41807cd2b4ce13c65e/href</a></iframe><p>That’s it. You made it. If you run yarn dev and you’re able to get to your app through your normal Valet url, then you got it right. You should also be able to get to it without the dev server running if you first run yarn prod.</p><p>Vite has quickly become a big part of the tools I use daily. Let me know if you find all this useful.</p><h3>One last stab at some self promotion</h3><p>You don’t have to do this yourself every single time because I did it for you. I have a simple Laravel package called Vitamin which you can find <a href="https://github.com/tpg/vitamin">here</a>. It’s this simple:</p><pre>composer require thepublicgood/vitamin</pre><pre>php ./artisan vitamin:init</pre><p>It’s early days, so let me know if you find it useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b8b825b790a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Saying PHP Is Dead.]]></title>
            <link>https://medium.com/swlh/stop-saying-php-is-dead-9489ed7dc25e?source=rss-b9992064b5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9489ed7dc25e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[language]]></category>
            <dc:creator><![CDATA[Warrick Bayman]]></dc:creator>
            <pubDate>Wed, 02 Dec 2020 20:33:52 GMT</pubDate>
            <atom:updated>2021-01-27T15:43:31.406Z</atom:updated>
            <content:encoded><![CDATA[<h4>It isn’t. PHP is not dead. It isn’t dying and it isn’t reaching “end-of-life”. That’s it. No matter how much some people want it to go away, it isn’t going away. At least, not for a long time.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ERM4E5Swb4D1bH0ngWdGxA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@greystorm?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ian</a> on <a href="https://unsplash.com/s/photos/death?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I’ve been writing this for a while now. Tweaking here and there, but just couldn’t decide when to publish. With the recent release of PHP 8, “now” felt like the right time.</p><p>Every month I read an article, or a comment or tweet stating that PHP is dying and we should stop using it. If you see a question on some or other forum or on Stack Overflow about learning PHP, there is an almost 100% chance that there’s a response from someone saying something like: “why would you want to learn PHP? Learn something cool like &lt;insert-cool-language-that-isnt-php-here&gt;”.</p><p>I have spent close on 20 years writing stuff in PHP (actually, it might be more. I don’t truly remember when I started), among other languages, and, for the most part, I have simply ignored much of that side of the conversation. For almost all of those years, PHP has been “dying” and I should’ve stop using it years ago. I am by no means an expert in any of the languages I use, and I have plenty to learn about PHP, yet time and time again, I find myself coming back to it.</p><p>I’ve spent plenty of hours learning other languages when I was almost convinced by the occasional well written anti-PHP piece. And I’ll admit that those adventures yielded great results. Although I’ll likely never use many of them professionally, I learnt so much about being a programmer just by learning another language.</p><p>If there’s one thing you take from this post, it should be: “learn another language”, but not because “php is dying” – It’s just not true. You should learn another language because it’s good for you as a programmer. If PHP really was dying, then sure, you’d have a reason to move on, but right now, in this moment, it isn’t dying.</p><p>One of the first things that many PHP programmers will bring up when trying to defend their choices, is one of those graphs showing how popular PHP is around the web. Although those numbers are very interesting I have a tendency to believe that they’re a bit misleading. It would be a mistake to ignore the fact that PHP is popular because of the likes of WordPress. Love it or hate it, WordPress is the reason we’re all here. But WordPress is… well… WordPress. It has many (and I mean many) faults, but I know (and am friends with) plenty of people who make a great deal of amazing things – And plenty of money – using WordPress.</p><p>PHP is not WordPress. And, although WordPress is firmly cemented into PHP’s history book, PHP is better than WordPress – MUCH better. There’s a lot wrong with WordPress and there’s a lot wrong with PHP, but that doesn’t mean its a bad choice for every project. I probably wouldn’t be writing my web applications in C++ (or at least it would be WAY down the list of languages for those projects), but that doesn’t make C++ a bad language. It’s just not suited for that job in the same way that I wouldn’t be using PHP to write hardware drivers or anything to do with AI. it’s just way outside of its wheelhouse.</p><p>Choice of language also has a lot to do with what you know. As the old adage goes: time is money, and in most cases, taking on a new language for a project is a big undertaking that would put more strain on timeframes which are usually already tight. I know PHP fairly well so it’s often going to be my first choice. I know a little Python, but I’m way better with PHP. I could probably do the same things in Python, but it’s going to take me twice as long, (at least in the beginning). It doesn’t mean I won’t use Python at all, or that I have anything against Python, it just means that PHP is my go-to.</p><p>Learning a language isn’t actually that hard and an experienced programmer might be able to pick up the gist of a language in a weekend. But that doesn’t mean they <em>know</em> the language. Knowing a programming language isn’t just about knowing which built-in function does what, it’s about having enough experience to know WHEN to use what features, or how the ecosystem fits together.</p><p>I know PHP, but I also know how to set up an Nginx web server and how to configure FPM or opcache; I have enough knowledge to make smart choices about dependencies; I know how to securely deploy PHP applications in production and I’m aware of security problems that could be introduced if I’m not careful with how I use certain language features. These things are more than just “knowing” a language. As programmers we invest a large amount of time in learning these things that often sit outside of the languages we choose.</p><p>That’s why it’s really disappointing when another programmer, tells me my choice of language is “shit”. I’ve spent 20 odd years getting better at this bit of technology, but now this one person is telling me that my choice was wrong?</p><p>Well, it’s not wrong. PHP has giving me a career I am happy with. I live in a nice house and drive a great car because I spent 20 years getting really good at this one thing.</p><p>But I digress. This was supposed to be about how PHP is not crap.</p><p>A lot of the “we hate PHP and think it should die” crowd bring up a number of things that they think make PHP an all-round bad choice. Some of those things we’ve been hearing for years and are based on long distant versions of PHP (I don’t know why everyone is still so focused on PHP 4, I mean seriously?). Other things are simply baseless and untrue. This isn’t a “my language is better than your language” rant, and I honestly believe that every programming language has a purpose. The people who bring these things into the world (who are all a lot clever than me) generally do so for good reason. Programming languages usually don’t happen by mistake.</p><h4>So, Why PHP?</h4><p>The answer is simple: because it was there. I’m self-taught, and I don’t have much in the way of formal training. Except maybe for the occasional online course I’ve taken, I have no piece of paper with a stamp on it from a prestigious university that says I can tell computers what to do.</p><p>I come from a design background, and although I’ve been tinkering with computers and code since I was like 7 years old, I didn’t follow that passion in education. I’m not even sure why. I like computers, and I like the internet, but instead… I chose graphic design. I’m not going to go into all that because, although I have a degree, it doesn’t really play much part in what I do today.</p><p>I came to PHP like I believe most PHP programmers do. Because we wanted a way to make a website do more than display a picture and a paragraph of text. I was so excited when I figured how to get stuff out of a database and display it on a web page. It was mind blowing! This was exactly what I needed and I dove in head first.</p><p>Then, I found WordPress. And like every other whippersnapper in front of a computer screen with some basic PHP knowledge, WordPress changed everything. This was cool, right?</p><p>WordPress owes it’s success to people like me. All us young kids that wanted a blog but didn’t have the knowledge to build them ourselves.</p><p>You installed WordPress… Then you added a plugin, and you changed the theme... Then you made a small change to the theme so it did something else, or looked a little different. Then you modified a plugin. Then you made your own theme. Then you thought to yourself… What else can I do?</p><p>And so I was introduced to PHP. I didn’t choose PHP, it chose me. 20 years later, and I’m still building things in PHP. Sure, not really with WordPress anymore, and I like to think I’ve matured as a PHP programmer to know how to write this post.</p><h4>“PHP is too easy. You should learn something difficult.”</h4><p>One of the big reasons PHP is so popular is because it’s so ubiquitous. It’s installed almost everywhere. Hell, even your average MacBook comes with PHP pre-installed (although that looks like it will be changing in a future version of MacOS).</p><p>It’s also really easy to write PHP from the word go. You usually don’t need to do anything special. Create an index.php file and put a single line of PHP in it and upload it to pretty much any shared hosting account:</p><pre>&lt;?php<br>echo &#39;Hello, World!&#39;;</pre><p>And you’re done. Starting out with PHP is really easy because you really don’t need to also know how to make PHP work. It’s almost always already been done for you.</p><p>However, if you can believe it, this “ease of use” is actually one of the complaints about PHP. The theory goes that if PHP is so easy, then it’s also really easy to write really dangerous code in PHP.</p><p>I’ve always felt a little uneasy about this idea. Is the suggestion then that languages which are harder to use are less likely to be used to create bad code? I read somewhere that something like 70% of the patches that Microsoft release for Windows are to address memory problems introduced because of C++ (don’t quote me on that though). I doubt that the people who write C++ for Microsoft are amateurs, and I’m pretty sure they know what they’re doing. Yes, Windows is far more complex than your average shopping cart website, but I think the argument stands. I disagree that PHP being easy to to use is what makes it dangerous. Python is highly regarded as beginner friendly, yet doesn’t get the same “dangerous” reputation. It’s easy to write dangerous code in ANY language. It’s not the language that makes code dangerous, it’s the lack of knowledge.</p><p>“Easy” is not a reason to discourage beginners from learning PHP, but rather, a reason to give those beginners better tools to make better decisions about the code they write. It’s a reason to help them find the right resources to learn PHP correctly. I was pretty lucky; and although I’ve written my fair share of “dangerous” code, there have been some well placed individuals in my life (not always PHP programmers) that have helped me figure out where to improve.</p><h4>PHP is slow</h4><p>Well, that’s not true. PHP is as fast or as slow as the code you write. PHP is a scripting language, so it’s pointless to compare it to compiled languages, yet for some reason I’ve even seen people compare PHP with Rust, or Go. Those are just not going to be valuable comparisons. Comparing it to Python or Ruby is probably better, but the “speed” of a language is dependent on a number of different factors. The language itself, yes, but also it’s environment, what code it’s running, how the interpreter is configured, etc. To say that PHP is slow without context is disingenuous.</p><p>PHP is definitely slow with regards to certain types of tasks. For example, PHP probably isn’t your first choice if you’re working in the machine learning space (although there are some very interesting projects that are showing some promise).</p><p>Sometimes, you’ll see benchmarks between two different languages doing the same thing, like looping over a million records and doing some simple calculation. The results are often milliseconds apart. This is sometimes used to show that PHP is slow (or fast, in some cases). If you are writing software where an extra few milliseconds when looping through a million records would be disastrous, then maybe you’re asking the wrong questions.</p><h4>WordPress is bad</h4><p>Yeah, I kinda agree. I’m not a the biggest fan of WordPress these days, but I’m also willing to admit that without WordPress we probably wouldn’t have the kind of PHP community we have today.</p><p>However, it’s also bad to judge a language because of one piece of software. That’s like saying C++ is a bad language because you don’t like Microsoft Windows.</p><p>PHP is not a one trick pony and WordPress is only one side of the PHP story. There are plenty of frameworks and packages to choose from if that’s the way you’d like to go. Laravel has been credited with “making PHP cool again”, and I have to admit that the framework is by far one of my favourites and an easy choice for me for most projects.</p><p>Blaming PHP for the misgivings of WordPress really isn’t fair. It could be argued that WordPress was a reflection of the limitations of PHP, but that was a long time ago, and the language has matured extensively since then.</p><h4>PHP isn’t enterprise ready</h4><p>Why? I really don’t get where this comes from. But it’s a big one. What makes a language “enterprise ready”? How is one language more enterprise ready than another? Java is probably one of the most popular languages in the enterprise space, but it’s not because Java itself is enterprise ready. It’s because of the existance of the Java EE Platform. I’m no Java developer, so I stand to be corrected here, but from what I understand, Java EE is a platform on which enterprise applications are built. Sounds kinda like a framework, right? So maybe the question should be “is &lt;my-favourite-php-framework&gt; enterprise ready?”</p><p>The answer to that question is for a different post entirely. The point I’m trying to make is that PHP as a language is as much “enterprise ready” as any other language. It depends entirely on how you use it.</p><blockquote>Just a side note, some time ago I was a part of a small team which built and deployed an events management platform onto the internal network of one of South Africa’s foremost financial institutions (I might write something about my experiences with that). The app was written entirely in PHP and JavaScript. And with the Covid-19 pandemic in full swing, the system was under extreme pressure, yet it has handled almost all of it. We’ve had a few hiccups, but nothing that couldn’t solved quickly.</blockquote><h4>PHP Doesn’t Scale</h4><p>This is the only one that has maybe a thread of truth to it, but it’s more complicated than you think. In truth, PHP is able scale just fine, if you write decent code. When people say that PHP doesn’t scale they usually referring to the idea that applications written in PHP might not be able to handle very large numbers of requests (like in the millions). The thing is that it’s still not that simple and I think a lot of the misconception comes from WordPress, which, until recently was well known for having scalability issues.</p><p>As a bit of proof, Slack, the messaging platform that tried to replace email, has milllions of users, all of whom connect every single day to a system who’s backend is written in PHP. If that’s not a story of how PHP can scale, then I don’t know what is. Many people cite Facebook as a good example, and although I believe Facebook probably still uses PHP in some form, I think they’ve probably moved much of their application away from PHP. But, to be honest, Facebook is a bit of a special case.</p><p>You can’t talk about scalability without also talking about infrastructure. If you’re hosting a WordPress blog on a simple shared hosting and you suddenly get tens of thousands of hits… well that could likely be a problem and your host is going to send you a nasty email, or at least bill you a lot more than you were expecting.</p><p>Scaling an application involves a lot more than just your language choice. There’s a lot of moving parts and I get frustrated when PHP takes the brunt of the blame. Newer versions of PHP, in the right environment and configured correctly, are more than capable of dealing with a large number of requests per second. Laravel Vapor, which is a first-party serverless platform for Laravel applications running on AWS, has some really impressive numbers.</p><p>I sometimes think the question of scalability is also a bit of an over exaggeration. In my 20 years of writing things in PHP, I have never had to deal with “millions of requests” per second. Not even close. The majority of us are not going to be building the next Facebook, no matter how much we like to dream about doing just that. In reality we build apps that are far more targeted. We deal with specific industries, often in specific countries and we never have to worry about dealing with more than a few hundred requests per second. For many of the projects we’re involved in, that would be large. It doesn’t mean that what we do isn’t important, it just means we don’t need to think about that sort of scale. Scaling applications to deal with millions of requests just isn’t a part of our normal day-to-day.</p><h4>PHP is Ugly</h4><p>You have to be kidding me. I’ve saved the most irritating for last. If you are selecting your tech stack based on how nice it looks, then you’re doing it wrong and you need to seriously re-evaluate your choices.</p><p>But even still, I don’t really think it’s true. It probably comes from the age old practise of using PHP directly in HTML (whish <em>is</em> ugly). The thing is: we really don’t do that anymore. In fact, it’s seriously frowned upon.</p><p>I’m not saying that so called “beautiful languages” are bad choices, but it definitely should not be your determining factor. Java is downright ugly, yet is one of the world most popular languages. Arguing against the use of PHP because it is ugly is just silly.</p><p>PHP probably isn’t the most beautiful language, but I find it’s quite readable when well written. And PHP 8 brings some really great tools to help make your code even more “beautiful”.</p><h4>I love PHP</h4><p>I really do. I love the language and the ecosystem. I love how it’s been improving over the last few years. PHP 8 is not just another iteration of the same language. With each major release we get better and more useful tools.</p><p>I love that PHP is easy to get started with, but I also love that it’s complex and there’s actually so much to know to be considered a professional PHP programmer. I love Symfony and Laravel and think that people behind them are as much responsible for pushing the language forward as the PHP core team is.</p><p>But mostly I love being a programmer. Not just in PHP, but I love creating stuff in any language that I happen to use. I love the fact that I can tell computers what to do and that I taught myself how to do that. I owe that to PHP. Without PHP, I don’t know what I’d be doing now. Maybe I’d be some mediocre designer hating my job and my life (no offence to any designers reading this. I have really talented designer friends who also love what they do). But instead I get to do something I love to do, using a language I love to use.</p><p>The end.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9489ed7dc25e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/stop-saying-php-is-dead-9489ed7dc25e">Stop Saying PHP Is Dead.</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Browsersync and Inertia.]]></title>
            <link>https://warrickbayman.medium.com/browsersync-and-inertia-8e3ed647669a?source=rss-b9992064b5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e3ed647669a</guid>
            <category><![CDATA[inertia]]></category>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[browsersync]]></category>
            <dc:creator><![CDATA[Warrick Bayman]]></dc:creator>
            <pubDate>Wed, 04 Mar 2020 21:25:27 GMT</pubDate>
            <atom:updated>2021-02-11T18:49:36.270Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tired of those XMLHttpRequest CORS policy errors? Me too.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sm8-aoTkr4WtGJ65kPxo_Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@andreapalaciosi?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Andrea Palacios</a> on <a href="https://unsplash.com/s/photos/dance?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Here’s a quick one on using Browsersync with Inertia. If you’ve ever tried and you got hung up on those pesky CORS errors that prevent redirects, then maybe I have a workaround for you.</p><h4>The bit about Browsersync</h4><p><a href="https://www.browsersync.io/">Browsersync</a> is one of those tools that just sticks. It has fantastic staying power. When I started building stuff for the web, LiveReload was all the rage. I loved that I could put my browser on one screen, my editor on another and not need to manually refresh every time I needed to see a change. It would just update whenever I saved stuff.</p><p>LiveReload eventually fell out of favour (is it even still a thing? I don’t know) and I went off to find an alternative. It didn’t take me long to come across Browsersync. It kinda did the same thing LiveReload did, but without the need to install that UI app. It’s a node dependency in the actual project, and it worked nicely with Webpack (also a recent discovery at the time).</p><p>Browsersync works by proxying your dev environment URL. Instead of visiting your site at whatever.test, you get a proxy url at localhost:3000. BrowserSync then automatically inserts a bit of JavaScript that does some magical things. Not only do you get an auto-reload when you save project files, but it will keep browsers in sync (hence the name) while you browse the site. Open two different browsers and point them both at localhost:3000. Now browse around your site and the other browser will follow along. It really <em>is</em> just like magic.</p><p>It’s become an invaluable piece of my toolkit and not one I’m going to give up without a fight.</p><h4>The bit about Inertia</h4><p><a href="https://inertiajs.com/">Inertia</a> is (as you may have guessed) a JavaScript framework. It’s not just another Vue or React, but rather a compliment to those frameworks. Jonathan Reinink, who wrote Inertia, calls it the “modern monolith” and I think that’s a fairly apt description.</p><p>In very basic terms, Inertia replaces your Blade templates with Vue templates. You get all the benefits of a regular, multi-page, Laravel powered application, but with all the cool, reactive stuff that having a modern, single-page, Vue powered application brings. It means you don’t need to do SPA authentication (which is just the worse thing you’ll have to deal with when building SPAs) because Laravel will manage your sessions for you, but you get fancy JavaScripty stuff that makes you look cool.</p><p>Inertia is still pretty new, but I’ve used it in a bunch of places already and I find that I immediately miss it when I have to work on projects where Inertia wasn’t used.</p><h4>The problem</h4><p>So if Browsersync is fantastic, and Inertia is a little piece of Laravel developer heaven, what could possibly be the problem? Well, the problem isn’t really a problem at all. It’s actually a good thing. It’s a simple piece of security baked into all our browsers called CORS.</p><p>CORS (Cross Origin Request Sharing) is designed to help prevent cross-site request forgeries. It’s intention to either give or deny an application running at one domain access to the resources of an application running at a very different domain.</p><p>As a security measure browsers prevent JavaScript applications from making requests across origins. When working with Browsersync, you’re actually working with two different origins. Your dev environment URI ( whatever.test ) and the proxy URI served by Browsersync ( localhost:3000 ). From the browsers point of view, that’s two distinct origins. The result is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*HrC1sI3GCS-pDIDaWHTxLg.png" /><figcaption>CORS policy ruing your day</figcaption></figure><p>It’s frustrating, but it’s also kind of a good thing. You don’t really want to break this stuff because it’s actually going to make your life easier later on.</p><h4>The quick solution</h4><p>So there are two solutions to this. The first thing that you might come across is why not just set the CORS headers to allow the different origins access to each others resources? That’s not a bad idea, but if you don’t have any intention of making cross origin requests outside of your dev environment, then this feels a little like breaking the wheel, then re-inventing the wheel, and then changing the wheel again before going into production.</p><p>Setting up CORS correctly takes a bit of time and can be a little tricky. There are a few packages around that attempt to make the process easier, but you’ll need to go read up a bunch about CORS first. Note that I’m not advocating for ignoring CORS at all. You definitely should go and learn about what CORS is and why it’s causing these errors in the first place, but sometimes I just don’t think it’s necessary to change the browser defaults.</p><p>Instead, there is a really simple solution and is requires two tiny changes.</p><p>First, update your Browsersync config and add the open option and set it to false. If you’re a Laravel Mix user, you can do this with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d93f8458a47ef3cbf33dd602d423af1/href">https://medium.com/media/7d93f8458a47ef3cbf33dd602d423af1/href</a></iframe><p>If you’re not a mix user, I’m sure you can translate the above into whatever you’re using. The Browsersync options are the same regardless.</p><p>To be honest, this first change isn’t all that necessary, but it will stop the browser from opening automatically which gets a little annoying eventually. Especially when your default browser isn’t the one you use for development (yes, I’m weird like that).</p><p>Next, add this small addition to your app.blade.php file that you created when you were setting up Inertia.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f03924476712da38a574e033b8d7989/href">https://medium.com/media/1f03924476712da38a574e033b8d7989/href</a></iframe><p>And here’s the really big change… Don’t visit <a href="http://localhost:3000/">http://localhost:3000</a> anymore and instead use your dev URL. So <a href="http://whatever.test/">http://whatever.test</a> (or <em>whatever</em> yours happens to be).</p><p>You’ll still get all that magical Browsersync goodness, and you can continue to use Inertia as before. There’s no need to go fiddling with CORS headers (which would have been a much bigger, and more time consuming change).</p><p>The app()-&gt;isLocal() means you don’t need to worry about it being used in production so you can just leave it there. As long as you’re environment isset to local and you have Browsersync watching your project, you can carry on as normal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e3ed647669a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dead simple permissions for Laravel]]></title>
            <link>https://warrickbayman.medium.com/dead-simple-permissions-for-laravel-94d23f55fea9?source=rss-b9992064b5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/94d23f55fea9</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[permission]]></category>
            <dc:creator><![CDATA[Warrick Bayman]]></dc:creator>
            <pubDate>Wed, 04 Mar 2020 19:11:55 GMT</pubDate>
            <atom:updated>2020-03-04T19:11:55.567Z</atom:updated>
            <content:encoded><![CDATA[<h4>Permissions can be complex. Here’s an easy solution.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i2eNIzyvs8EPwzb9ZuKOWQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@zenking?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Rob King</a> on <a href="https://unsplash.com/s/photos/lock?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote>tl;dr: If you’re not interested in setting this up yourself and would rather just install a package, I wrote one called Deadbolt. Check it out on <a href="https://github.com/tpg/deadbolt">GitHub</a>.</blockquote><p>I’ve built a number of Laravel applications over the years and most of them had some sort of authorisation requirement. Some users should have access to certain resources, while other users should not. It’s easy, right? Add a boolean column to your users table that gives users access to that resource if it’s set to true. Done!</p><p>Sure, that works. But it’s really not very flexible. What happens when you have lots of resources? What if you need to protect other parts of your application? That simple boolean “flag” is quickly going to show its shortcomings. This is where you quickly start to realise that you need some form of permissions system. Luckily there are quite a few really awesome solutions to choose from, but by far the most popular (for good reason) is the <a href="https://github.com/spatie/laravel-permission">laravel-permission</a> package from the guys at <a href="https://spatie.be/">Spatie</a>. It has everything you could possibly want out of a permissions package for Laravel. If you’re looking for a really flexible, feature-rich permissions package, then that is definitely the right way to go. But every now and again, you just don’t need all of that. Sometimes, all you really want sits somewhere <em>between</em> the boolean flags and the power of Spatie’s solution.</p><p>I think that the approach I describe here fills that gap. It’s simple and is especially useful when you’re dealing with an SPA frontend (or my favourite at the moment: <a href="https://inertiajs.com/">IntertiaJS</a>). The idea is that you store assigned permissions directly in your users table as a JSON encoded string which is then available every single time you reference the User model. No need for additional database tables.</p><p>I’ve also never really felt comfortable storing application permissions in a database table. Roles, sure, but permissions are often tied to the actions they authorize. Those actions generally are not described in a database table, so why do we do so with the permissions that authorise them?</p><p>Okay, let’s get on with it, then.</p><h4>Update the user table migration</h4><p>First, we need a place to store the permissions we’re going to give our users. I’ve already said that we’ll store assigned permissions right in the users database table. So update your users database table migration to include a permissions column.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7a3f176775dd54791521cde02b023a8/href">https://medium.com/media/e7a3f176775dd54791521cde02b023a8/href</a></iframe><p>We’ll need to update our User model to cast that column as a JSON object. Add the following protected property to User.php:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c71293c091c99eeea4a9f263563792a/href">https://medium.com/media/1c71293c091c99eeea4a9f263563792a/href</a></iframe><p>Now when we use $user-&gt;permissions, we’ll get a PHP array of the permissions assigned to that user. That’s already better than the series of boolean flags I mentioned earlier.</p><p>Just remember that string columns usually have a fixed length. If you have lots of permissions, you might need something a bit longer.</p><h4>Define the available permissions</h4><p>You can define a new config file for this, but it’s perfectly fine to add things to the config files that are already included with Laravel. That’s kinda what they’re there for, anyway.</p><p>Add a new array to the end of the auth.php file in your config directory. We’ll use this to list the actual permissions we can potentially give to users.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a21a79069b053e96b6d53de2c9b93d1/href">https://medium.com/media/3a21a79069b053e96b6d53de2c9b93d1/href</a></iframe><p>The useful part of this is that we can now get a list of available permissions using the config helper method:</p><pre>$permissions = config(&#39;auth.permissions&#39;);</pre><p>We can already start assigning permissions to our users when updating or creating them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f61a60b19cf5f9d04fb1a8aa1ad9beb0/href">https://medium.com/media/f61a60b19cf5f9d04fb1a8aa1ad9beb0/href</a></iframe><h4>Using Laravel policies</h4><p>I strongly recommend that you use policy classes to authorise actions on resources. As an example, let’s say we have an Article model that represents blog articles in our database. Our users should have separate permissions to create, edit or delete articles. We can create a new policy for articles using a simple Artisan console command:</p><pre>php ./artisan make:policy ArticlePolicy</pre><p>This will create a new /app/Policies/ArticlePolicy.php file. We can create methods in there that represent the actions we want to authorise. Write create, edit, and delete methods that return a boolean. We’ll simply check if the required permission is in the array of permissions we can get from the User model passed into the method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63337572d9957b9341f4175393696cbf/href">https://medium.com/media/63337572d9957b9341f4175393696cbf/href</a></iframe><p>Now that our policy is complete, Laravel provides a simple authorize method that you can use from within your controllers that will let you authorize users using the policy class we created. So for example, in our create method on our ArticleController class, we can do this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d06d7318853d1dcc06d71b4667b4a78f/href">https://medium.com/media/d06d7318853d1dcc06d71b4667b4a78f/href</a></iframe><p>As a user, if you now try to make a request for the /articles/create URI and the articles.create permission doesn’t exist in your permission array, you’ll get a 401 Unauthorized error.</p><p>That’s pretty simple, and easy to set up. It’s not all that easy to use right now. Especially if you’re going to need to check more than one permission.</p><h4>Create a service class</h4><p>Let’s create a simple service class that we can reach for when we need to manage a users permissions. That way we don’t need to mess around with the user model directly and we can add some useful additional features along the way. Create a new file called Services/PermissionService.php. We’ll write a few simple methods to help manage the permissions for our users. Let’s start with something simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a8aca96ebde4de3a9c6ca69032c523c/href">https://medium.com/media/8a8aca96ebde4de3a9c6ca69032c523c/href</a></iframe><p>Right now, all this class can do is return an array of the permissions we put into the auth.php config file. That’s not exactly exciting, or particularly useful. So let’s add a method that we can use to give our users new permissions.</p><p>We don’t want to add permissions that don’t actually exist, so we’ll first check that a permission is in the array we added to the auth config. Only permissions that are in that array will then be added to the user. Let’s write a give method that takes a User instance and an array of permissions which we can call when we’re ready to assign permissions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9fea695b73aecb7542c1fc2067653ad/href">https://medium.com/media/b9fea695b73aecb7542c1fc2067653ad/href</a></iframe><p>This method returns the service class itself so we can chain methods together if we want. Also, it might be better to rather fail here if a permission doesn’t exist instead of simply ignoring it. That way, you’ll be able to catch potential typo’s you might have missed.</p><p>We can also add a super method which will automatically give the user ALL the available permissions in one go. The super method just calls the give method and passes in all the available permissions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55cc76fbaac4dc795b9e43386856670c/href">https://medium.com/media/55cc76fbaac4dc795b9e43386856670c/href</a></iframe><p>Okay, great! We can give users permissions. But what if we want to take permissions away? Let’s write a revoke method and a clear method to do just that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afe0f4a808c420a47119c5b6c3735160/href">https://medium.com/media/afe0f4a808c420a47119c5b6c3735160/href</a></iframe><h4>Create a facade</h4><p>I’m not going to explain facades here. You can read up about how facades work in the <a href="https://laravel.com/docs/7.x/facades">Laravel documentation</a>. Just know that a facade is a really easy way to create a new instance of a class and get access to the methods on that class through a nice, easy-to-read interface.</p><p>You could easily use this service class without the facade if you don’t want to write a facade, but it does makes it a little sexier. So create a new class in Facades/Permissions.php:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f0833c02b6c4e9332f67eca0626bb2f/href">https://medium.com/media/2f0833c02b6c4e9332f67eca0626bb2f/href</a></iframe><p>The facade will simply tell Laravel how to find the service class we already created. We do this by using a “key” that we’ll bind into the Laravel container. The facades getFacadeAccessor method should return that key.</p><p>Once you’ve got your facade all sorted out, we need to register it. This is commonly done in the AppServiceProvider in your Providers directory. Update the register method with the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/398268ba18ceb7ace64c0cf20a67490f/href">https://medium.com/media/398268ba18ceb7ace64c0cf20a67490f/href</a></iframe><p>That’s all we need to do to get the facade registered. Now we can use our new facade like this:</p><pre>Permissions::give($user, [&#39;articles.create&#39;]);<br>$user-&gt;save();</pre><p>How about testing permissions though? At the moment, our ArticlePolicy class is checking if a user as a permission by checking if that permission exists within the array stored in the permissions column. There’s nothing really wrong with that, but we can do better. So let’s add a method to the PermissionService that we can use to test if a user has a specific permission. We’re just moving the in_array logic from the policy into our service class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d75e16f56704ccfeeb8c35db43ab6a2/href">https://medium.com/media/1d75e16f56704ccfeeb8c35db43ab6a2/href</a></iframe><p>Now let’s update the ArticlePolicy class so that it uses the Permissions::has() method we just created:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93ae21ac10b92d75e9e534634e5a03d9/href">https://medium.com/media/93ae21ac10b92d75e9e534634e5a03d9/href</a></iframe><p>And done!</p><p>That’s it. If we need to add permissions to our system, we just update the permissions array in the auth.php config. We can add policies as we need and use the facade to give and revoke permissions. There’s a lot of room for improvement here, but the idea was to create something simple that is a little more flexible than adding an admin boolean column.</p><h4>And JavaScript…</h4><p>If you need to have access to the users permissions from within a JavaScript app, because Laravel will do the hard work for you by returning an array of your User model, you get the cast permissions array as well for free! And since PHP arrays can easily be encoded as JSON strings, there’s really not much you need to do to get the users permissions available in your JavaScript client.</p><p>I like using InteriaJS at the moment, so if I return the user to an Inertia page from a controller method like this:</p><pre>return Inertia::render(&#39;Pages/Articles/Create&#39;, [<br>    &#39;user&#39; =&gt; Auth::user(),<br>]);</pre><p>… in my Vue template I can easily do something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1a467eb7a46d6aaa734f0c0e04d095a/href">https://medium.com/media/b1a467eb7a46d6aaa734f0c0e04d095a/href</a></iframe><p>No need to make extra HTTP requests to the application just to check if a user has permission to complete a task. I have the user object, so I have their permissions as well. If I share the authenticated user with all my Inertia views then I have those permissions everywhere, which is really handy.</p><h4>The Package</h4><p><em>Waring! Blatant self-promotion ahead…</em></p><p>I’ve used this approach a few times now, and even in one fairly large project and it works like a charm. Anyway, to make my life easier, I created a package for Laravel called <a href="https://github.com/tpg/deadbolt">Deadbolt</a> and it’s similar to what I’ve described here, but with perhaps a little more grace and elegance, if I say so myself. The package has a bunch more features than this article and is probably a lot less error prone, but the basic idea is the same.</p><p>The package is MIT licensed, so use how you want. It’s still fairly new, but I’m using it a bunch at the moment, so it currently gets fairly regular updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94d23f55fea9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero Downtime Laravel Deployments with Envoy—Version 2!]]></title>
            <link>https://warrickbayman.medium.com/zero-downtime-laravel-deployments-with-envoy-version-2-227c8259e31c?source=rss-b9992064b5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/227c8259e31c</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[envoy]]></category>
            <dc:creator><![CDATA[Warrick Bayman]]></dc:creator>
            <pubDate>Tue, 17 Dec 2019 16:02:29 GMT</pubDate>
            <atom:updated>2019-12-30T18:30:24.407Z</atom:updated>
            <content:encoded><![CDATA[<h4>I’ve grown, I’ve learned some stuff, I’ve broken some other stuff. So I think it’s about time I did…</h4><h4>My first attempt at zero downtime deployments was exactly what I needed a few years ago. But now, I have something better.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKxUqyyjps0wZdv2WZmaVg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@helloimnik?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Hello I’m Nik 🇬🇧</a> on <a href="https://unsplash.com/s/photos/rocket?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>A few years ago, I wrote an <a href="https://medium.com/@warrickbayman/zero-down-time-laravel-deployments-using-envoy-b0d1f0fddb81">article on how to use Envoy to run zero-downtime deployments</a>. That article has been a somewhat popular one. It still gets around 100 reads a week, which I don’t think is all that bad considering I’m definitely NOT a professional writer. That approach to deployment was great and it’s a method I’ve used for quite some time. It has, however, started to show its limitations—especially since it’s not “just me” anymore.</p><p>I’ve always been a bit of a lone programmer. I studied graphic design many years ago, but it just wasn’t my cup-o-tea. I left design for web development in my 20s and basically taught myself everything I know (thanks to a decent collection of some well written books and some strategically placed people in my life), and I’ve never looked back. Like many who teach themselves, PHP and JavaScript quickly became my thing, and I’m now massive fan of Laravel with a fair amount of experience.</p><p>A lot of the decisions I would make were based around the idea that no one else would ever need to work on the same projects. That all changed just a few years ago. My life’s story isn’t really the point of this article, so I’ll fast forward just a little… I now have the privilege of working with a great team. It’s awesome, but it meant that I needed to make some changes to how I worked.</p><h4>A Quick Recap</h4><p>Zero-downtime deployments are exactly what you would think they are. It means you deploy your application without ever needing to take the site offline. Sounds magical, but it’s really not all that hard:</p><ol><li>Get the code on the server (ftp, ssh, git, whatever floats your boat);</li><li>Do all the bits that you would normally do to make the site work, like installing dependencies;</li><li>Create a symbolic link to the location of the site;</li><li>Get the web server to serve the symbolic link.</li></ol><p>Ready to deploy a new version? Just repeat those same steps again. The current running version doesn’t get removed until the last step when you create a new symlink. Since all the actual deployment tasks, which take so much longer to complete, have already been done. The web server simply continues to serve the same symlink. Except now it’s serving your new version… with zero downtime.</p><p>If you don’t want to do this yourself, there’s a few tools that you can use instead. Take a look at <a href="https://envoyer.io/">Envoyer</a> if you’d rather not be messing about on the server yourself. And if you’re a Laravel developer, Envoyer is a no-brainer.</p><p>But, if you like how this sounds and you’re not afraid to get your hands dirty, then you’ll be happy to know that making it work really isn’t difficult.</p><blockquote>This article is not a continuation of my previous post on the same topic, so you don’t need to go back and read that one first. However, if you’re interested in how I got to this point, take a look at my first version <a href="https://medium.com/@warrickbayman/zero-down-time-laravel-deployments-using-envoy-b0d1f0fddb81">here</a>.</blockquote><p>Since I wrote that first article I’ve spent a fair amount of time working with other programmers and we’ve used that approach, or a version of it, quite extensively. We’re not alone, either. If you take a look around the web, you’ll find a whole bunch of articles that describe similar solutions. It definitely works for more programmers than just me. However, you’ll start to eventually realise that there’s a bit of a problem with it.</p><h4>The Compiled Assets Problem</h4><p>Our websites and webapps contain a lot of stuff. And if you’re like me, then you’re compiling assets using a whole collection of different tools. We write a lot of stuff using things like SASS, and we often have plenty of Vue components. Those files need to go through a build step so that we end up with stock standard CSS and JavaScript files that the browser understands.</p><p>I’m a big fan of WebPack and we use Laravel Mix for most build tasks and usually end up with at least two files: app.css and app.js. We also use code splitting a lot through the use of the Babel dynamic imports, so we’ll often end up with a few extra JavaScript files. Regardless, the build process generally remains the same.</p><p>The resulting assets then need to exist on the server but how do we get them there? Well, that’s easy right? we commit them to the repo and clone the repo to the server. If you read my first article then you’ll know that’s exactly what we were doing. We git clone directly onto the server as part of our deployment and be done with it. We don’t need to install any fancy build tools on the server (which, to me, feels akin to taking the contents of your entire kitchen on a road trip) and we know we’ll have a correctly compiled asset on the server.</p><p>So what’s the problem? Well, now that I’ve been working with a team of my own, it’s very common for multiple programmers to be working on the same project. Each programmer is compiling assets on their own machines and committing to the repo. Those compiled assets can get pretty large, which was now causing chaos with pull-requests. Our git history was a mess and diffs were impossible to deal with. It’s clear that committing compiled assets to our repo wasn’t going to be right thing to do anymore.</p><h4>The Missing Piece</h4><p>We’re getting to the solution, I promise. It just felt like I needed to write this fascinating back story first…</p><p>I started reading around the web and I found a ton of people struggling with the very same issue. Some devs say you should compile on the server (yuk) and others said I should continue committing to the repo. Others agreed that having compiled assets in the repo was a bad idea, but didn’t really have a nice solution to getting those assets onto the server (nobody wants to FTP, right?). I knew I still wanted to use git clone to get code onto the server, but didn’t want compiled assets in the repo at all.</p><p>Then it hit me. Why not just copy them there? Sounds so rediculously simple. Compile the assets locally, and just upload them to the server using scp.</p><h4>The Solution</h4><p>After I put some thought into this, here’s what I eventually decided needed to happen. It’s not all that different from my old deployment process, but it has one magical extra step:</p><ol><li>Add all compiled JavaScript and CSS files files to my .gitignore file.</li><li>I use Laravel Mix, so I’ll also add the mix-manifest.json file to .gitignore as well.</li><li>Run yarn prod to build production ready assets.</li><li>git clone the production branch onto the server.</li><li>Run composer install --no-dev on the server.</li><li><strong>Use </strong><strong>scp to copy the compiled assets into the correct directories on the server.</strong></li><li>Create a symlink that points to the new public directory that’s been created.</li><li>The web server serves the new symlink.</li></ol><p>There is exactly one extra step there: step 6. Everything else is pretty much the same as before.</p><h3>Making it work</h3><p>With most projects we work on, we follow a slightly modified version of Gitflow. I’m not going to detail that here, but it’s worth noting that we generally end up with at least two branches in all our repos. We have a master branch and a develop branch. All work gets merged into develop during development and eventually merged into master which is always a reflection of what is on the production server. We also tag our releases, but that’s just for our own sanity and gives us something to reference when talking about different stages of the project.</p><p>Before we can write any deployment scripts, we need to do some set up on the server. We use Nginx as our own web servers and we run Ubuntu Server whenever we can. However, that’s really not important here, as long as your web server can serve symbolic links. If you’re an Apache user, you’ll probably need to add something like Options +FollowSymLinks to your web server config.</p><p>I’m also assuming that you’ve set up your keys correctly and you’re able to log into the server using your private SSH key. If you’re still logging in with a password, I strongly recommend you consider setting key pairs and disabling password logins on your server.</p><h4>Step 1: Ignoring some stuff</h4><p>We first need to ensure that we’re not committing all those compiled assets to our repo any longer. We need to ignore any .js files in /public/js and any .css files in /public/css and the mix-manifest.json file. Let’s first update the root .gitignore file to ignore the mix-manifest.json file. Simply add the line:</p><pre>/public/mix-manifest.json</pre><p>Cool. Now create a .gitignore file in both the /public/js and the /public/css directories and add the following:</p><pre>*<br>!.gitignore</pre><p>This will make sure that we ignore all the files in those directories except the .gitignore itself. That way at least the directory is still created with nothing in it.</p><p>Remember to commit your changes.</p><h4>Step 2: Server set up</h4><p>We need to define how our environment looks on the server. I like to use the /opt directory, but it’s entirely up to you. I’ll often create a directory named after the vendor inside /opt and a directory for the project inside that. Then we need a directory to place our releases. For clarity I’ll name it releases. So here’s what we should have to start with:</p><pre>/opt<br> |<br> +- /vendor<br>     |<br>     +- /project<br>         |<br>         +- /releases</pre><p>Now we can clone into that releases directory So from within the releases directory, run:</p><pre>git clone --depth 1 -b master git@gitlab.com:project.git initial</pre><p>Obviously, you’ll replace that Git URL with the one for your project. That line will shallow clone the project and checkout the master branch into a directory named initial. Now we have a copy of the project on the server.</p><p>Before you carry on, it’s important to know that you’re going to need Composer installed on the server. If you haven’t done so already, you can get it installed by running:</p><pre>curl -sS <a href="https://getcomposer.org/installer">https://getcomposer.org/installer</a> | php<br>sudo cp composer.phar /usr/local/bin/composer</pre><p>Now you can run composer from anywhere on the server. If you need more instructions on this, take a look at the <a href="https://getcomposer.org/doc/00-intro.md#installation-linux-unix-macos">Composer documentation</a>.</p><h4>Step 3: .env and storage</h4><p>Next we’ll need to make a copy of our .env.example file. If you’re a Laravel user, you’ll already know what that file is for. Normally it sits at the root the your project, however, since we’ll be cloning a new copy of the code each time we deploy, we’ll need to keep a copy of the .env out of the way so it doesn’t get lost between deployments. That way we can reuse the same file each time we run our deployment script. A good place for it is in /opt/vendor/project since it will be relative to the project as a whole. So:</p><pre>cp /opt/vendor/project/releases/initial/.env.example /opt/vendor/project/.env</pre><p>We need to do the same thing with the storage directory. You’re probably using the storage directory already to store stuff for your project and you won’t want to loose the content in there each time you run a new deployment. Also, Laravel stores session data here and we don’t want to destroy users sessions each time we deploy. We can put the storage directory in the same location as the .env file we already copied.</p><pre>cp -r /opt/vendor/project/releases/initial/storage /opt/vendor/project</pre><p>The -r option will copy the directory recursively so we don’t leave anything behind. All this should result in the following layout:</p><pre>/project<br> |<br> +- /releases<br> |  |<br> |  +- /initial<br> |<br> +- /.env<br> |<br> +- /storage</pre><p>Now we can remove the copy of the /storage directory from within our project (since we’ll use the one we just created) and we can create symlinks to both the .env file and the storage directory we copied.</p><p>First, remove the storage directory:</p><pre>rm -rf /opt/vendor/project/releases/initial/storage</pre><p>Now create the links:</p><pre>ln -nfs /opt/vendor/project/storage /opt/vendor/project/releases/initial/storage</pre><pre>ln -nfs /opt/vendor/project/.env /opt/vendor/project/releases/initial/.env</pre><p>Let’s take a look at our layout again:</p><pre>/project<br> |<br> +- /releases<br> |   |<br> |   +- /initial<br> |       |<br> |       +- /.env -&gt; /opt/vendor/project/.env<br> |       |<br> |       +- /storage -&gt; /opt/vendor/project/storage<br> |<br> +- /.env<br> |<br> +- /storage</pre><p>Great! We’re getting somewhere. This is starting to look similar to how the old deployment looked. However, notice that the /releases/intial/public directory has an empty /js and an empty /css directory. Since we’re not including those compiled assets in the repo anymore we now need to copy them into the correct location. That’s our next step.</p><h4>Step 4: Assets</h4><p>It’s time to compile some assets. On your own computer and from within your project, run your build script and compile production ready assets. For me, this is offen as simple as:</p><pre>yarn prod</pre><p>Once you’ve got a set of new assets, let’s get them onto the server:</p><pre>scp -rq public/css/ user@server.com:/opt/vendor/project/releases/initial/public</pre><pre>scp -rq public/js/ user@server.com:/opt/vendor/project/releases/initial/public</pre><pre>scp -q public/mix-manifest.js user@server.com:/opt/vendor/project/releases/initial/public</pre><p>Not overly complex. We’re using scp to copy the entire contents (including directories: that’s the -r option) of the /public/css and the /public/js from our local copy into the server. We’re also copying the mix-manifest.json file to the server.</p><p><strong>Step 5: Composer and Laravel</strong></p><p>Now that we have everything in place we can install Composer dependencies and get our Laravel app into a running state. First, we need a key:</p><pre>cd /opt/vender/project/releases/initial</pre><pre>php ./artisan key:generate</pre><p>Remember that we have a symlink of the .env file in our releases/initial directory, which means that actual .env file, sitting in /opt/vendor/project will now contain a new APP_KEY value.</p><p>Next, dependencies:</p><pre>composer install --no-dev --prefer-dist</pre><p>We don’t need development dependencies on the server, and the --prefer-dist flag will get Composer to leave out any development specific files from our dependencies that are not needed on the server.</p><p>Now’s a good time to complete any extra steps you need for the initial installation of your application. For example, maybe you need to create a new database and migrate the tables:</p><pre>php ./artisan migrate</pre><p>Maybe you need to update the .env file with any third-party API keys you’re using. Before putting your application live, you’ll want to complete those tasks first.</p><h4>Step 6: Live!</h4><p>Our journey is at an end! Well, sort of… If we’ve done everything correctly, we should have a working application. All we have to do is create a new symbolic link to the /public directory that the web server will serve:</p><pre>ln -nfs /opt/vendor/project/releases/initial/public /opt/vendor/project/live</pre><p>Update your web server config to point to /opt/vendor/project/live…</p><p>And voila! Let’s take one last gander at our layout with the new symbolic link in place:</p><pre>/project<br> |<br> +- /releases<br> |   |<br> |   +- /initial<br> |       |<br> |       +- /.env -&gt; /opt/vendor/project/.env<br> |       |<br> |       +- /storage -&gt; /opt/vendor/project/storage<br> |<br> +- /.env<br> |<br> +- /storage<br> |<br> +- /live -&gt; /opt/vendor/project/releases/initial/public</pre><p>As long as the web server is configured to serve the /opt/vendor/project/live symlink then each time you deploy, you can simply replace that symlink and your new deployment will automatically become the one your users see.</p><p>If you’ve got this far, then great success! But now we need to automate this whole thing. It’s really not feasible to follow all these steps every time you need to deploy a new version of your app. At some point you’ll mess it up and then you have an app offline. We’re trying to avoid that situation, so let’s rather automate the steps using a simple Envoy script.</p><h4>Step 7: Envoy</h4><p>Envoy is one of the most useful tools (besides Laravel itself) to come out of the Laravel ecosystem. It’s a simple task runner based on Laravel blade. It can be used to run tasks both locally and on a remote server. Envoy is dead simple and you can find a bunch of info in the <a href="https://laravel.com/docs/envoy">Laravel documentation</a>.</p><p>First, you’ll need to make sure you have Envoy installed. You can install it globally on your computer with Composer:</p><pre>composer global require laravel/envoy</pre><p>Now create a new file in your project root called Envoy.blade.php, and start with the following content:</p><pre>@servers([&#39;local&#39; =&gt; &#39;127.0.0.1&#39;, &#39;production&#39; =&gt; &#39;user@server.com&#39;])</pre><pre>@setup<br>    // any setup will go here<br>@endsetup</pre><pre>@story(&#39;deploy&#39;)<br>    build<br>    git<br>    install<br>    live<br>@endstory</pre><pre>@task(&#39;build&#39;, [&#39;on&#39; =&gt; &#39;local&#39;])<br>@endtask</pre><pre>@task(&#39;git&#39;, [&#39;on&#39; =&gt; &#39;production&#39;])<br>@endtask</pre><pre>@task(&#39;install&#39;, [&#39;on&#39; =&gt; &#39;production&#39;])<br>@endtask</pre><pre>@task(&#39;assets&#39;, [&#39;on&#39; =&gt; &#39;local&#39;])<br>@endtask</pre><pre>@task(&#39;live&#39;, [&#39;on&#39; =&gt; &#39;production&#39;])<br>@endtask</pre><p>Before we go any further, let’s take a look at what we have here. The servers bit at the top defines the servers you’ll be deploying to. You could define a staging, UAT or production server here. For now, I just have a production one set, and a local which is set to 127.0.0.1. Envoy will let us run tasks locally if we use that as the target server. Just a note: that first line might look like a PHP array, but there is one requirement… It must exist on a single line. Don’t break the array up over multiple lines, Envoy won’t know what to do with that.</p><p>We have five task blocks. Namely: build, git, install, assets and live. Each one is also added to a story block that will execute them in sequence so we don’t need to run each one separately.</p><p>If you’re coming from the old article, then that script should look somewhat familiar.</p><p>The @setup block lets us run some simple PHP before the tasks are executed. Let’s add some setup stuff that we can use throughout the script to make our jobs a little easier.</p><pre>@setup<br>    $repo = &#39;git@gitlab.com:project.git&#39;;<br><br>    $branch = &#39;master&#39;;<br><br>    date_default_timezone_set(&#39;Africa/Johannesburg&#39;);<br>    $date = date(&#39;YmdHis&#39;);<br><br>    $appDir = &#39;/opt/vendor/project&#39;;<br><br>    $buildsDir = $appDir . &#39;/releases&#39;;<br><br>    $deploymentDir = $buildsDir . &#39;/&#39; . $date;<br><br>    $serve = $appDir . &#39;/live&#39;;<br>    $env = $appDir . &#39;/.env&#39;;<br>    $storage = $appDir . &#39;/storage&#39;;<br><br>    $productionPort = 22;<br>    $productionHost = &#39;user@server.com&#39;;<br><br>@endsetup</pre><p>That should be fairly self-explanitory, but let’s go through it anyway:</p><ul><li>$repo is the repository that we’ll clone from;</li><li>The $branch variable is just the branch in the repo that will be cloned to the server;</li><li>The $date variable is used to create unique directories inside the releases directory;</li><li>The $appDir is the absolute location to the project;</li><li>the $buildsDir points to the /releases directory we created earlier;</li><li>The $deploymentDir is the one we’ll clone into. Note how I’ve used the $date variable here;</li><li>The $serve variable is where the live symlink is created;</li><li>The $env variable points to the actual .env file we copied;</li><li>The $storage variable points to the actual storage directory we copied;</li><li>And lastly, the $productionHost and $productionPort is used by the assets task when copying the compiled assets to the server;</li></ul><p>It’s stock standard PHP and all we’re really doing is setting some variables. It shouldn’t be hard to see what’s going on here. Now we can flesh out the tasks. Let’s start with the build task.</p><pre>@task(&#39;build&#39;, [&#39;on&#39; =&gt; &#39;local&#39;])<br>    yarn prod<br>@endtask</pre><p>Yup. That’s it. All it’s doing is building the production ready assets locally. Now for the git task:</p><pre>@task(&#39;deployment&#39;, [&#39;on&#39; =&gt; &#39;production&#39;])<br>    git clone --depth 1 -b {{ $branch }} &quot;{{ $repo }}&quot; {{ $deploymentDir }}<br>@endtask</pre><p>Also simple. We’re creating a shallow clone of the master branch into a directory on the server. Now the install task:</p><pre>@task(&#39;install&#39;, [&#39;on&#39; =&gt; &#39;production&#39;])<br>    cd {{ $deploymentDir }}<br><br>    rm -rf {{ $deploymentDir }}/storage<br><br>    ln -nfs {{ $env }} {{ $deploymentDir }}/.env<br>    ln -nfs {{ $storage }} {{ $deploymentDir }}/storage<br><br>    composer install --prefer-dist --no-dev<br><br>    php ./artisan migrate --force<br><br>    php ./artisan storage:link<br>@endtask</pre><p>That’s our first complex task. There’s a few things happening here, but if you take a hard look, it’s all the tasks we’ve done before:</p><ul><li>We’re change into the new deployment directory,</li><li>remove the storage directory (we have one we’ll use, remember),</li><li>Create a symlink to the .env file,</li><li>Create a symlink to the storage directory,</li><li>Run Composer to install dependencies,</li><li>Migrate any database changes,</li><li>Create a symlink to the storage/public directory (optional if you use this),</li></ul><p>We have our compiled assets waiting paciently so now is the time to get those in place. Here’s the assets task:</p><pre>@task(&#39;assets&#39;, [&#39;on&#39; =&gt; &#39;local&#39;])<br>    scp -P{{ $productionPort }} -rq ./public/js/ {{ $productionHost }}:/opt/vendor/project/public<br>    scp -P{{ $productionPort }} -rq ./public/css/ {{ $productionHost }}:/opt/vendor/project/public<br>    scp -P{{ $productionPort }} -q ./public/mix-manifest.json {{ $productionHost }}:/opt/vendor/project/public<br>@endtask</pre><p>And finally, the live task:</p><pre>@task(&#39;live&#39;, [&#39;on&#39; =&gt; &#39;production&#39;])<br>    ln -nfs {{ $deploymentDir }}/public {{ $serve }}<br>@endtask</pre><p>The last task simply creates a live symlink and points it to the new deployment. And we’re done! We’ve basically taken all the steps we did earlier and repeated them in the Envoy script. Now whenever you need to deploy a new copy of your application into production, simply navigate to your project directory and run:</p><pre>envoy run deploy</pre><p>and the whole thing will happen all over again. You still get the same old zero-downtime deployment as before, but now there are zero compiled assets in your repository. For teams, this is a godsend because you can now keep your commits cleaner and pull requests are no longer the nightmares they were.</p><p>Since we create a new directory every time we deploy, we have a copy of the old one still sitting on the server. This means that if something terrible goes wrong after you’ve deployed, you can simply replace the live symlink and point it to the previous deployment.</p><p>Here’s the whole Envoy script in all its glory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a451467a9643fd6514ce3676a06c0365/href">https://medium.com/media/a451467a9643fd6514ce3676a06c0365/href</a></iframe><h3>But wait… There’s more!</h3><p>This is pretty damn awesome I think. It’s made mine and my teams lives so much simpler. We use this approach for a lot of the web work we do (with a variation here or there). However, I’ve been working on much bigger projects these days and even this approach still isn’t perfect.</p><p>I’ve spoken a few times about the potential of using this approach in a CI/CD pipeline but never actually having done it myself. Well, it was about time I did… so I did. That’s my next post. I’ll show you how to get a CI/CD pipeline to build, run your unit tests and your deployment script for you. And I’ll write about how to set up multiple environments, so keep an eye out for that one. I’ll update this post with a link when that one is ready.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=227c8259e31c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sub-domain “Profiles” in Laravel]]></title>
            <link>https://warrickbayman.medium.com/sub-domain-profiles-in-laravel-47028ae4e009?source=rss-b9992064b5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/47028ae4e009</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[profile]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[domains]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Warrick Bayman]]></dc:creator>
            <pubDate>Thu, 05 Jul 2018 15:12:11 GMT</pubDate>
            <atom:updated>2019-03-11T21:17:08.530Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>2019/03/03:</strong> I recently updated this post, and there’s quite a number of changes I’ve made. The old post was fairly outdated and needed some attention.</blockquote><p>I work on a lot of apps that load up an “organisation” or “client” profile based on a sub-domain slug. It’s quite common in multi-tenant applications. This is something we do on <strong>MotorPress</strong> (<a href="https://motorpress.co.za/">https://motorpress.co.za</a>) and it works really well, so I’ll use that as an example.</p><p>Each publisher on MotorPress gets their profile. They can publish content to the main MotorPress feed, or exclusively to their own branded, public profile feed. We provide each publisher with their own sub-domain. So we end up with something like this:</p><pre>https://motorpress.co.za/<br>https://vw.motorpress.co.za/<br>https://audi.motorpress.co.za/<br>https://toyota.motorpress.co.za/</pre><p>The bit before the “motorpress.co.za” domain is a unique “slug” that each publisher is assigned. If a visitor finds their way to each of those profile pages they’ll see a slightly different version of the MotorPress home page. Each branded exclusively for that organisation.</p><p>It turns out that Laravel provides a toolset that makes this sort of thing really easy to achieve. Here’s an example of how we do it.</p><h4>The database</h4><p>We’ll need to store the organisation slugs somewhere. You’ll want to include a slug column in your organisations (or whatever your organisational units are called) table. An updated up method in the migration file might look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/356f70d15c8c28071bec4657be1dab8c/href">https://medium.com/media/356f70d15c8c28071bec4657be1dab8c/href</a></iframe><p>In the example, the slug must be unique and a maximum of 40 characters long. You’ll probably have some other details in there as well.</p><h4>Generating slugs automatically</h4><p>I have a SlugService which we use to generate unique slugs for each organisation. There’s plenty of packages out there that do this as well, so you can decide if you want to do this yourself or use one of those. A good one to look at it <a href="https://github.com/spatie/laravel-sluggable">https://github.com/spatie/laravel-sluggable</a> from Freek Van der Herten.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23f39e372812e9bdc8d735ee3251a4ff/href">https://medium.com/media/23f39e372812e9bdc8d735ee3251a4ff/href</a></iframe><p>You can make a call to the uniqueSlug method to generate a new slug for any model. Pass in the model instance, the source for the slug and the name of the column where the slug will be stored. So it can be used like this:</p><pre>(new SlugService())-&gt;uniqueSlug($organisation, &#39;title&#39;, &#39;slug&#39;);</pre><p>And since I want to do this automatically, I can use the creating model event which will fire each time a new Organisation instance is created. I’ll add this to the boot method of the Organisation class:</p><pre><em>static</em>::creating(<em>function </em>(Organisation $organisation) {<br>    $organisation-&gt;slug = $organisation-&gt;slug ?:<br>        (<em>new </em>SlugService())-&gt;uniqueSlug($organisation);<br>});</pre><p>By using $organisation-&gt;slug = $organisation-&gt;slug ?: ... I can pass in an different slug if I need to, otherwise the uniqueSlug class in the SlugService will generate a new slug for me based on the organisation title.</p><h4>Dealing with the request</h4><p>Laravel allows me to hook into the request lifecycle really easily through the use of middleware. In this case, I want to create a middleware class that will sort out the organisation profile before the request hits the router. So I have a middleware class named SetOrganisationProfile. Artisan has a make:middleware command that makes this real easy:</p><pre>php ./artisan make:middleware SetCompanyProfile</pre><p>The handle method in any middleware is generally where most of the action happens. However, since I don’t like having very long methods I’ll often move a lot of this logic into something like a ProfileService which I reply on when I need profile information. This is a fairly opinionated approach and you may have a completely different solution, but this gives me a service that I can use elsewhere if needed. I sometimes like to create facades that make access to those services even easier. I’ll get to that a little later.</p><p>Here’s how my app/Services/ProfileService.php :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12b2640bc246a90a26af26161c938715/href">https://medium.com/media/12b2640bc246a90a26af26161c938715/href</a></iframe><p>This isn’t actually that complicated, really. The middleware, when we get to it, will make a call to the getProfileOrganisation method and pass in the Request object. The getProfileOrganisation method will in turn make a call to the getProfileSlugFromRequest method to get the actual slug from the URL, and then pass the slug to the getProfileOrganisationFromSlug method to get the associated Organisation model. I’ve also added an ignoreSlugs array to the class with a specified list of slugs that should be ignored. For example, I sometimes have an images slug.</p><p>You may notice the extractDomainFromApplicationUrl protected method. This service assumes that I’ve got <a href="https://motorpress.co.za/">https://motorpress.co.za</a> set as the APP_URL in my .env file. If you have a www in the domain name, then you’ll need to update this method accordingly. A super quick way to do that is just change +3 to a +7 (“://www.” is 7 characters long).</p><pre><em>return </em>substr(<br>    config(&#39;app.url&#39;),<br>    strrpos(config(&#39;app.url&#39;), &#39;://www&#39;) +7);</pre><p>That will return motorpress.co.za. Anything before that string, in my case anyway, is a slug. That’s where the getHostSlug method comes in which will assume that if the actual host is longer than the domain we extracted, then there must be a slug prefix. We then make sure that the prefix doesn’t exist in the ignoreSlugs array, and return the result.</p><p>Okay, now onto that Middleware.</p><h4>The middleware</h4><p>Since the service is doing the heavy lifting as far as the request is concerned, I can keep my middleware class nice and light:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25a81af1a5f82b7b092755cd591a7806/href">https://medium.com/media/25a81af1a5f82b7b092755cd591a7806/href</a></iframe><p>So when a request is made, the handle method gets called and a Request object gets passed in. A new instance of the service is created and the request gets passed to the getOrganisationProfile method of the ProfileService class and hopefully I get an Organisation instance back. If the organisation doesn’t exist, I’ll get null.</p><p>If we don’t get a Organisation instance back but there definitely is a slug in the URL, then, I’ll usually bail out here with a 404 response. This is where the hasSlug method on the service to check comes in. I don’t do anything special here and Laravel’s abort helper does exactly what I need.</p><p>If there is a Organisation model then I can put the instance onto the Session, and also share it with any views that might need access to it. There’s two protected methods for that: updateSession and shareWithViews respectively.</p><p>Lastly, I just need to ensure that the middleware is registered by adding it to the list of middleware in app/Http/Kernel.php. I usually add it to the web middleware group:</p><pre>&#39;web&#39; =&gt; [<br>    \App\Http\Middleware\SetOrganisationProfile::class<br>],</pre><p>I usually don’t use this any API stuff, but it’s something you need then you won’t be able to use the session to store the profile since API’s are inherently stateless. In that case, you can just make a call to the getOrganisationProfile method on the ProfileService as you need to.</p><h4>Facades</h4><p>So this is just a little update that makes accessing those services a little easier if you want to go this route. I like using facades in Laravel as they feel more expressive and they look neater. But again, this is opinionated and I suppose there’s other ways to do this.</p><p>Since facades are not essential to the running of my app, I think of them as support classes. They’re really handy, but not a requirement. Therefore they go in an app/Support/Facades directory. First I’ll create a Profile facade class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2e4e9655cf87359e5614bc5d7991006/href">https://medium.com/media/a2e4e9655cf87359e5614bc5d7991006/href</a></iframe><p>The facade needs to be registered, so in AppServiceProvider:</p><pre><em>public function </em>register()<br>{<br>    $this-&gt;app-&gt;bind(&#39;profile&#39;, <em>function </em>($app) {<br>        <em>return new </em>ProfileService();<br>    });<br>}</pre><p>Now I don’t need to new up an instance of ProfileService myself and I don’t need to inject it into a constructor. I can simple do:</p><pre>use App\Support\Facades\Profile;</pre><pre>...</pre><pre>$profile = Profile::getProfileOrganisation();</pre><p>That’s it. There’s been a few other ideas pop up around this topic lately. This is just something I’ve been using for some time.</p><h4>Where to from here</h4><p>I suppose there’s a lot you could do with this idea now. For example, you could update the getProfileOrganisation method to return the Organisation instance that’s on the session if it exists instead of pulling the instance from the DB again (if you’re using the facade method). You could create a facade for the SlugService as well, which is something I’ll do sometimes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47028ae4e009" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero downtime Laravel deployments using Envoy]]></title>
            <link>https://warrickbayman.medium.com/zero-down-time-laravel-deployments-using-envoy-b0d1f0fddb81?source=rss-b9992064b5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0d1f0fddb81</guid>
            <category><![CDATA[envoy]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Warrick Bayman]]></dc:creator>
            <pubDate>Sun, 18 Mar 2018 20:17:29 GMT</pubDate>
            <atom:updated>2019-12-17T18:31:05.583Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lVoNtIIAkqwdo7Opj6s1PQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/FgY6bF6emj0?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sam Xu</a> on <a href="https://unsplash.com/search/photos/stop?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote><strong>Update 2019–12–17:</strong> I’ve written a second version of this deployment process. This article is still entirely relevant, but if you want a slightly updated process, <a href="https://medium.com/@warrickbayman/zero-downtime-laravel-deployments-with-envoy-version-2-227c8259e31c">take a look here</a>.</blockquote><p>Envoy is one of the most useful tools in the Laravel ecosystem and I use it almost every day. Nearly every project I work on gets it’s own Envoy script to makes deployments super simple.</p><p>Envoy is a task runner, and a simple one at that. It’s not Laravel specific (it’s not even PHP specific) but does make use of the blade templating language as a way to script actions. So Laravel developers will feel immediately comfortable. Although you could use Envoy to write deployment scripts for pretty much any tech you happen to be using, I’m only going to deal with Laravel here. However, I don’t think it would take much to to get it working for anything else.</p><p>Like other Laravel tools, Envoy is installed using composer and should be easy to set up as part of your CI/CD workflow. If you don’t already have it installed, then a simple composer global require laravel/envoy should be all you need.</p><p>Envoy uses a really simple configuration. For really basic sites I’ll often use something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/324ed7a6e62139f7ede0d43fcf62764c/href">https://medium.com/media/324ed7a6e62139f7ede0d43fcf62764c/href</a></iframe><p>All that really does is pull any changes on the master branch into the local copy on the server. It then runs a composer self-update and a composer install. The cp line is something that I use when dealing with Laravel on Hetzer SA. <a href="https://medium.com/@warrickbayman/hosting-laravel-apps-on-hetzner-sa-d8a7c0d38162">I wrote a little about that</a>, if you’re interested.</p><p>You could also expand on this a little. For example, If you need database migrations you could add a line of php artisan migrate. It also wouldn’t be a bad idea to put your site in maintenance mode while this is all happening as it could take a little while to complete all these tasks and you don’t want visitors to see odd error messages. For Laravel apps: artisan down and artisan up are probably a good idea.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b1368b9709e97e7069b707dfbda5c80/href">https://medium.com/media/3b1368b9709e97e7069b707dfbda5c80/href</a></iframe><p>This works quite well and is a really nice, simple way to deploy basic sites. But there’s a few small problems. Firstly, you have to take your site offline, which means no one can get to it. For busy sites that’s really not something you want to do without having a REALLY good reason. You could schedule your updates for times when your site is less busy, but that’s just another task that has to be managed, and it’s STILL downtime. Well, I have a better way…</p><h3>Getting to Zero</h3><p>Let’s say you’ve built an app that has gained some popularity and you’re getting quite a few logins a day. Nice. Now you discover a bug that could be effecting a number of your hard earned users. So you fix the bug, run your tests and all it good, so now you need to get the changes into production. The previous example will work great, but as we know, it has a few problems. And what if more problems arrise during deployment that you didn’t plan for? It could mean your app is offline for an extended period of time. Not good.</p><p>Ultimately you need to get your new version into production without breaking what is already there. Zero downtime deployments do take a little bit of planning, but it’s actually not that hard. For Laravel apps, here’s what I do. I think you could do this with other tech or frameworks without changing all that much.</p><ol><li>Instead of serving an actual directory, make a small change and point your web server to a symlink of the application directory. You’ll probably need to make some changes to your web server config so that it will follow symbolic links.</li><li>Clone your repository into a new directory.</li><li>Copy the storage directory and the .env file out of the project directory and place them somewhere they won’t get lost. We’ll create links to them soon.</li><li>Run composer install and, if needed, php artisan migrate --force in the new directory to install new dependencies and migrate any database changes.</li><li>Create a new link inside the project directory to the storage directory you copied out earlier. Do the same with the .env file you copied so that you now have two symbolic links inside the project directory.</li><li>Create the symbolic link that points to your project and that your webserver will serve.</li><li>Get a coffee.</li></ol><p>That’s it. Zero downtime deployments for Laravel. Better yet, we can put all this into an Envoy script that we can run just once. If anything goes wrong, your current deployment will remain since the symlink is created in the last step and it only happens once everything else has been completed first.</p><h3>The Setup</h3><p>Before you begin with all this, you’ll want to make sure that your web server config is set up to allow symbolic links. If you’re an Nginx user, you probably don’t need to do anything. For Apache, however, you’ll probably need to add something like this to your config:</p><p>Options +FollowSymLinks</p><p>Without it, Apache won’t know what to do with the symbolic links that you’ll create.</p><p>I like to put apps in the /opt directory under the name of the app. So something like /opt/my_app. I then create a sources directory. You can call it anything you like. Deployments then always go into the sources directory and get sym-linked as source (although that happens last).</p><p>Clone a new copy of your app into the sources directory. You can call it anything you want for now, but I usually stick with initial. Later on, you’ll write an Envoy script that will use the current date for the name of the directories that you clone into.</p><pre>git clone -b production &quot;<a href="/service/mailto:git@bitbucket.org">git@</a>repository.git&quot; sources/initial<br>cd sources/initial</pre><p>Now sort out the storage directory and the .env file.</p><pre>cp /opt/my_app/sources/initial/.env.example /opt/my_app/.env<br>cp -r /opt/my_app/sources/initial/storage /opt/my_app/storage<br>rm -rf /opt/my_app/sources/initial/storage</pre><pre>ln -nfs /opt/my_app/.env /opt/my_app/sources/initial/.env<br>ln -nfs /opt/my_app/storage /opt/my_app/sources/initial/storage</pre><p>Which should result in the following layout:</p><pre>/opt/my_app/sources/initial<br>/opt/my_app/storage<br>/opt/my_app/.env</pre><pre>/opt/my_app/sources/initial/.env  — &gt; /opt/my_app/.env<br>/opt/my_app/sources/initial/storage  — &gt; /opt/my_app/storage</pre><p>We’re into the home stretch.</p><pre>composer install -o --prefer-dist --no-dev<br>php ./artisan migrate --force</pre><p>Any Laravel developer should be fairly comfortable with that. The composer line will install composer dependencies and optimize the autoloader. Follow that up by making sure that any database changes are migrated. Don’t forget to generate a new key and make any changes to the .env file that you need.</p><pre>php ./artisan key:generate</pre><p>Everything should be up and running now. The point of all of this is that you can now clone the repository into a new directory and simply replace the source link and your new version will be up and running.</p><pre>ln -nfs /opt/my_app/sources/intial /opt/my_app/source</pre><p>Your web server should now serve the source link.</p><h3>Envoy</h3><p>All of this is great, but it’s not exactly a quick process. And it’s complex enough that mistakes can easily creep in. This is where <strong>Envoy</strong> steps in. You can take everything that you’ve now done and stick it into an Envoy script which will do everything automatically. Here’s the basic layout I like to use for my Envoy script:</p><pre>@servers([&#39;production&#39; =&gt; &#39;user@server.com&#39;])</pre><pre>@setup<br>    // any setup will go here<br>@endsetup</pre><pre>@story(&#39;deploy&#39;)<br>    git<br>    install<br>    live<br>@endstory</pre><pre>@task(&#39;git&#39;, [&#39;on&#39; =&gt; &#39;production&#39;])<br>@endtask</pre><pre>@task(&#39;install&#39;, [&#39;on&#39; =&gt; &#39;production&#39;])<br>@endtask</pre><pre>@task(&#39;live&#39;, [&#39;on&#39; =&gt; &#39;production&#39;])<br>@endtask</pre><p>Since Envoy is a task runner, we can separate our deployment script into tasks. You don’t really need to do this, though. You could have just one task that does everything. The @setup block allows for any setting up you might need to do, like defining a few variables that can be used in the tasks. I’ll often use something like this:</p><pre>@setup<br>    $repo = &#39;git@repo.git&#39;;<br>    $appDir = &#39;/opt/my_app&#39;;<br>    $branch = &#39;production&#39;;</pre><pre>    date_default_timezone_set(&#39;Africa/Johannesburg&#39;);<br>    $date = date(&#39;YmdHis&#39;);</pre><pre>    $builds = $appDir . &#39;/sources&#39;;<br>    $deployment = $builds . &#39;/&#39; . $date;</pre><pre>    $serve = $appDir . &#39;/source&#39;;<br>    $env = $appDir . &#39;/.env&#39;;<br>    $storage = $appDir . &#39;/storage&#39;;<br>@endsetup</pre><p>This should be fairly self-explanatory. I’m creating a bunch of variables that I can use in the tasks just to make life a little easier. It also makes the script a little more reusable since I only need to change a few values under setup instead of throughout the script. The $date variable is used to name the directory we’ll clone the repo into and help ensure we’re not overwriting anything.</p><p>Time to flesh out the tasks. First the <strong>git</strong> task:</p><pre>@task(&#39;git&#39;, [&#39;on&#39; =&gt; &#39;production&#39;])<br>    git clone -b {{ $branch }} &quot;{{ $repo }}&quot; {{ $deployment }}<br>@endtask</pre><p>Fairly simple stuff. Note how the variables from setup now get used. Here’s the <strong>install</strong> task:</p><pre>@task(&#39;install&#39;, [&#39;on&#39; =&gt; &#39;production&#39;])<br>    cd {{ $deployment }}</pre><pre>    rm -rf {{ $deployment }}/storage</pre><pre>    ln -nfs {{ $env }} {{ $deployment}}/.env</pre><pre>    ln -nfs {{ $storage }} {{ $deployment }}/storage</pre><pre>    composer install --prefer-dist --no-dev</pre><pre>    php ./artisan migrate --force<br>@endtask</pre><p>And finally the <strong>live</strong> task:</p><pre>@task(&#39;live&#39; [&#39;on&#39; =&gt; &#39;production&#39;])<br>    ln -nfs {{ $deployment }} {{ $serve }}<br>@endtask</pre><p>If you wanted to, you could run each task from the command line. However, it’s way nicer to add a @story block so that all the tasks are run in sequence:</p><pre>@story(&#39;deploy&#39;)<br>    git<br>    install<br>    live<br>@endstory</pre><p>You’re done! Here’s the script in full:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9169727147671472ffc6ef91284fcb4e/href">https://medium.com/media/9169727147671472ffc6ef91284fcb4e/href</a></iframe><p>When you’re ready to deploy, all you need is:</p><pre>envoy run deploy</pre><p>If you think about it, the only variables that would need changing between different projects would be the $repo, $appDir, and maybe $branch. Simply copy the Envoy.blade.php file, and update the variables as needed.</p><h3>And Finally</h3><p>There’s a few added benefits to deploying this way. Obviously the zero-downtime is a massive plus, but you also suddenly get a copy of the previous deployment still sitting on your server.</p><p>Say you get through a deployment only to find that there’s been a horible mistake (god forbid). You can easily roll back to the previous deployment just by changing the source link. Using a date string to name those directories means that it’s also really simple to find the previous one.</p><p>Alternatively, instead of simply replacing the source link, you could rename it to something like backup and then create the source link to your new deployment. If you need to go back, simply delete the current source link an rename backup to source.</p><p>And if the deployment fails for some reason, no need to worry since the actual “making it live” bit is done right at the end. If something does go wrong, Envoy will bail out with something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*HoulFQYo7EVD9HHuhd-V0w.png" /><figcaption>Envoy task failure</figcaption></figure><p>The previous deployment is still running and untouched.</p><p>From here, the script could be modified to deploy to your testing and staging environments. Have a read through the Envoy documentation <a href="https://laravel.com/docs/envoy">here</a>. There’s a few other features that really make it super handy. You can even get it to notify your Slack channel.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0d1f0fddb81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A simple way to selectively load dev packages into Laravel]]></title>
            <link>https://warrickbayman.medium.com/a-simple-way-to-selectively-load-dev-packages-into-laravel-7eb6f8f18266?source=rss-b9992064b5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7eb6f8f18266</guid>
            <category><![CDATA[environment]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[service-provider]]></category>
            <dc:creator><![CDATA[Warrick Bayman]]></dc:creator>
            <pubDate>Mon, 28 Aug 2017 14:11:28 GMT</pubDate>
            <atom:updated>2018-07-10T18:21:05.962Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>NOTE: 18 October 2017</strong></p><p>So with the release of Laravel 5.5, this isn’t really needed anymore. Laravel 5.5 now has a package discovery feature so there is no need to add supported packages to your app.php config anymore. Simply install the package and you’re good to go.</p><p>Here’s a little snippit I use all the time. It allows you add packages to your Laravel installation selectively based on the environment you’re working in. There’s always those dev packages you don’t want, or shouldn’t have in production, so they get added to require-dev. Cool, but then you have non-production packages all over your app.php config file in production code. I think that’s crap.</p><p>So I wrote a super-simple Service Provider for Laravel that will let you load dev packages ONLY when working in your dev environment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/880390d33122ad7b605eabd7b0675b80/href">https://medium.com/media/880390d33122ad7b605eabd7b0675b80/href</a></iframe><p>Stick it in your Providers directory, and add the following line to the $providers array in config/app.php.</p><pre>App\Providers\DevelopementServiceProvider::class,</pre><p>Now you can add your dev packages to the $providers member array and they’ll only get loaded when your APP_ENV is local. You can also load facades selectively by listing them in the $facades member array.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eb6f8f18266" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>