Dockerize your Laravel app with Vessel

Chris Fidao has created an easy to handle, well documented, Docker dev environment for Laravel projects. It's an excellent starting point if you want to have a taste of what Docker can do. For the introductory newsletter:
I like Vessel the best for the following reasons: 1. It's installed per-project instead of globally. This lets me customize it per project if need be. 2. Docker lets me change out versions of software such as Nginx, MySQL, Redis, and others very easily. (I've often needed to use an older MySQL version at work) 3. Docker lets me add extra software (perhaps Beanstalkd for queues, or PgSQL for database) really easily 4. Docker containers are more like processes than VMs. They generally only use what resources they need (with some caveats, but even with those, they're lighter than Vagrant virtual machines) 5. I can fill up my workstation with one technology (Docker!) instead of many (PHP, Redis, MySQL, etc) with all their configuration files and data strewn about all over my file system 6. You can expand on your dev workflow to build up to a production workflow using all the same technology (Docker!) - You can check out Shipping Docker for my full course on bringing Docker from dev into production.

The official Vue.js style guide

The maintainers of Vue.js have recently published their official style guide.
This is the official style guide for Vue-specific code. If you use Vue in a project, it’s a great reference to avoid errors, bikeshedding, and anti-patterns. However, we don’t believe that any style guide is ideal for all teams or projects, so mindful deviations are encouraged based on past experience, the surrounding tech stack, and personal values. For the most part, we also avoid suggestions about JavaScript or HTML in general. We don’t mind whether you use semicolons or trailing commas. We don’t mind whether your HTML uses single-quotes or double-quotes for attribute values. Some exceptions will exist however, where we’ve found that a particular pattern is helpful in the context of Vue. Want to see some more style guides? At Spatie we have a guidelines site containing styleguides for Laravel and JavaScript.
This site contains a set of guidelines we use to bring our projects to a good end. We decided to document our workflow because consistency is one of the most valuable traits of maintainable software. The contents of this site exist for ourselves—more importantly, our future selves—and for giving future collegues a reference to our way of doing things and their quirks. The guidelines cover workflow, code style, and other little things we consider worth documenting.

Handling Stripe webhooks in a Laravel application

In the project I'm currently working on I had to integrate Stripe webhooks. Stripe has great documentation on how to handle webhooks, but it still took a fair amount of time to get the integration just right. My solution for handling webhooks is pretty generic and reusable by others. I decided to extract it to a package called laravel-stripe-webhooks, so nobody has to code this stuff up again. In this blogpost I'd like to share how the package works.

Requests will be validated

Whenever an event occurs on Stripe, the service will notify your app by sending a http request to your app. Here's a list of all events Stripe sends out. Stripe will sign all requests it sends to your app. This package will automatically verify if the signature is valid. If it is not, the request was probably not sent be Stripe.

Webhooks are restartable

Before doing any other work, all calls will immediately be logged to the database. This is incredibly valueable when something goes wrong handling a webhook call. You can easily retry the processing of the webhook call, after you investigated and fixed the cause of failure, like this:
use Spatie\StripeWebhooks\StripeWebhookCall;


Handling valid requests

There are two ways this package enables you to handle webhook requests: you can opt to queue a job or listen to the events the package will fire. In both cases we highly recommend queuing the job or queueing the event listener that does some work. By doing that, you can minimize the response time of the webhook requests. This allows you to handle more stripe webhook requests and avoiding timeouts. Let's take a look at both methods.

Using jobs

Laravel has a handy make command to scaffold a Job.
php artisan make:job ChargeSource
After that you must let the job accept a WebhookCall instance in it's handle method.
namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Spatie\StripeWebhooks\StripeWebhookCall;

class ChargeSource implements ShouldQueue
    public function handle(StripeWebhookCall $call)
        // do your work here

        // you can access the payload of the webhook call with `$webhookCall->payload`
After having created your job you must register it at the jobs array in the stripe-webhooks.php config file. The key should be the name of the stripe event type where but with the . replaced by _. The value should be the fully qualified name of the class.
// config/stripe-webhooks.php

'jobs' => [
    'source_chargeable' => \App\Jobs\StripeWebhooks\HandleChargeableSource::class,
And with that you job will fire when strips sends out the source.chargeable webhook.

Using events

Instead of queueing jobs to perform some work when a webhook request comes in, you can opt to listen to the events this package will fire. Whenever a valid request hits your app the package will fire a stripe-webhooks::<name-of-the-event>. For if a source.chargeable event hits your app, the stripe-webhooks::source.chareable event will fire. Let's take a look at how you can listen for such an event. In the EventServiceProvider you can register a listener.
 * The event listener mappings for the application.
 * @var array
protected $listen = [
    'stripe-webhooks::source.chargeable' => [
Here's an example of such a listener:
namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Spatie\StripeWebhooks\StripeWebhookCall;

class ChargeSource implements ShouldQueue
    public function handle(StripeWebhookCall $call)
        // do your work here

        // you can access the payload of the webhook call with `$webhookCall->payload`
Like already mentioned above, we highly recommend that you make the event listener queueable. The above example is only one way to handle events in a Laravel. To learn the other options, read the Laravel documentation on handling events.

In closing

Head over to the readme of laravel-stripe-webhooks on GitHub to learn a few more tidbits about the package. Rest assured that the package contains a suite of tests to make sure everything works correctly. Because Stripe is quite popular, I can image that a lot of artisans already have written their own implementation for handling webhooks. In my mind it's kind of silly that everybody has to code up the same solution over and over again. If you tackle a problem concerning common stuff consider open sourcing your solution. You will benefit yourself from the public scrutinization of your code (in mean this in a positive way). Your future self will be thankful for the documentation you write for your package. The other members of the community will be saved from writing the same boring code. And we all can get to building the fun and interesting stuff. If you're in a position in your company to advocate or to actively work on open source, I highly recommend you do so. There are only winners in this story! That being said, be sure to take a look at the collection of Laravel, PHP and JavaScript packages our team has created: Pretty sure there will be something there that can be helpful in one of your future projects.

Essential image optimization

Addy Osmani, a Google Chrome engineer, recently published a e-book on image optimization. You can read it in it's entirety here:
Images take up massive amounts of internet bandwidth because they often have large file sizes. According to the HTTP Archive, 60% of the data transferred to fetch a web page is images composed of JPEGs, PNGs and GIFs. As of July 2017, images accounted for 1.7MB of the content loaded for the 3.0MB average site. Per Tammy Everts, adding images to a page or making existing images larger have been proven to increase conversion rates. It's unlikely that images will go away and so investing in an efficient compression strategy to minimize bloat becomes important.
If you need to optimize images in your PHP application take a look at our image optimization package. If you're a Laravel user you'll be happy to know that there's also a Laravel version of the optimizer. Our Laravel Medialibrary also comes with built-in support for optimizing images.

Handling Stripe payments in Laravel

Povilas Korop, creator of Laravel Daily and Quick Admin Panel, wrote an extensive guide on how to integrate Stripe into a Laravel application.
Stripe is one of the most popular payment merchants for web, but information about Laravel integration is pretty fragmented, so I decided to write a really long tutorial about this topic. We will cover: - General logic how Stripe works - Simple one-time payment integration - Testing and production environment setup - Saving transaction data for future reference - Recurring payments with Laravel Cashier - Getting invoices data and PDF download

New features in our packages

Every time our team releases a package I have the habit of writing an introductory blogpost. But after the initial release most pages gain more features through PRs by the community and ourselves. Mostly these new feature go unnoticed. That's why I plan on regularly writings posts on noteworthy changes across our repos.


This package makes it easy to convert any webpage (or html string) to an image or a pdf. Under the hood headless Chrome is leveraged. A while ago I took the time to add a new bodyHtml method to it. Here's how that can be used:
The method returns the html of the dom after JavaScript has been executed. Pretty cool. Among our packages there's also a powerful crawler. bodyHtml paved the way for making that crawler execute JavaScript as well. So now it can also find links that were injected by JavaScript scripts on your site. Our laravel-sitemap package uses that crawler to automatically create a sitemap of your site. Now that the crawler can execute JavaScript, the sitemap generator can now add pages which are linked to by JavaScript injected links.


Our medialibrary is a pretty powerful package that can associate all sort of files with eloquent models. Here's a video that demonstrates what the package is capable of. A PR by Alex Vanderbist makes it possible to generate temporary URLs to files that are stored on S3. Here's how you can do that
   ->getTemporaryUrl(Carbon::now()->addMinutes(5), 'thumb'); // Temporary S3 url


This package makes it easy make eloquent models translatable. Translations are stored as json. There is no extra table needed to hold them. Previously a translation should be set like this:
$yourModel->setTranslation('name', 'en', 'Name in English')
A PR by flofloflo adds an alternative way to go about this:
// assuming your the locale of the app is set to `en`
$yourModel->name = 'Name in English
Feels much more natural.


Our demo mode package provides a middleware that can protect your work in progress from prying eyes. Visitors should first visit a specific (secret) url before they can see that content of the project you're building. A PR by Alex Vanderbist added these two options to the config file that make it possible to make a whitelist on an IP address basis.
 * The following IP addresses will automatically have access to the app
 * without having to pass the `demoAccess` route.
'authorized_ips' => [


 * If strict mode is enabled then only the IP addresses listed in `authorized_ips` are allowed.
 * Vistors won't be able to gain access by visiting the  `demoAccess` route anymore.
'strict_mode' => false,

Building an SMS admin powered by Laravel and Nexmo

JMac, the creator of Laravel Shift, shared how he can very easily spin up a new job on his service by sending a simple SMS message.
In the end, all I need is a quick way to run a Shift on the go. Looking back on almost two years of support, I often have the Shift number readily available. Creating the job and adding it to the queue is at most two lines of code. So the steps are not the pain point. The pain point is connecting to the server. Unless I want to carry my laptop around, I can’t connect to the server to run the Shift. (I actually have taken my laptop with me during peak times.) What do I carry around with me all the time? My phone. I’m already reviewing the support emails from my phone. Wouldn’t it be great when I need to run a Shift manually to just reply or send a text.

A trait to dynamically add methods to a class

We recently released our newest package called macroable. It contains a trait that, when applied to class, can dynamically add methods to that class. This trait is basically a stand alone version of the macroable trait in Laravel. In this post I'd like to show you how you can use it, how it works behind the scenes and explain why we created it.

How it can be used

Here's a simple example of how the trait can be used. In this example we are going to add concatenate method to an anonymous class. Of course you can use the trait on regular classes as well.
$myClass = new class() {
    use Spatie\Macroable\Macroable;

$myClass::macro('concatenate', function(... $strings) {
   return implode('-', $strings);

$myClass->concatenate('one', 'two', 'three'); // returns 'one-two-three'
Callables passed to the macro function will be bound to the class the trait is applied upon. Sounds scientific, here's an example to make that clear:
$macroableClass = new class() {

    protected $name = 'myName';

    use Spatie\Macroable\Macroable;

$macroableClass::macro('getName', function() {
   return $this->name;

$macroableClass->getName(); // returns 'myName'
You can also add multiple methods in one go my using a mixin class. A mixin class contains methods that return callables. Each method from the mixin will be registered on the macroable class.
$mixin = new class() {
    public function mixinMethod()
       return function() {
          return 'mixinMethod';

    public function anotherMixinMethod()
       return function() {
          return 'anotherMixinMethod';


$macroableClass->mixinMethod() // returns 'mixinMethod';

$macroableClass->anotherMixinMethod() // returns 'anotherMixinMethod';

How it works behind the scenes

The implementation of macroable is really simple. The name and the callable passed to macro is simply stored in an array.
//inside the trait 

protected static $macros = [];

 * Register a custom macro.
 * @param  string $name
 * @param  object|callable  $macro
public static function macro(string $name, $macro)
    static::$macros[$name] = $macro;
Whenever you call a function upon the class that does not exists the trait will try to find a macro with the name of the called function.
public function __call($method, $parameters)
    if (! static::hasMacro($method)) {
        throw new BadMethodCallException("Method {$method} does not exist.");
    $macro = static::$macros[$method];
    if ($macro instanceof Closure) {
        return call_user_func_array($macro->bindTo($this, static::class), $parameters);
    return call_user_func_array($macro, $parameters);
Even though there's a little bit more to it, that's basically the gist of it. An important bit to remember is that you can't use this trait on a class that implements __call itself.

Why we created the macroable package

You might wonder why you ever would need to use macroable in your project when you can just simply add methods to classes. Well, this macroable trait isn't really meant to be used in regular projects. It's more targeted at package and framework developers. By applying the trait to certain classes in a package users of the package can add methods to the classes of the package without changing the source code. In Laravel there are plenty of classes that are macroable. Take the Collection class for instance. Because it is macroable you can add your own custom methods to it without them having to be PRed (and accepted) to the framework. My team even released a package that contains a bunch of collection macros that are quite handy, but maybe not general enough to be added to framework. Want to know more about how macros can be used in Laravel? Then read this excellent piece by Caleb Porzio which contains a list of macroable things in Laravel. Besides Laravel specific ones, my team releases a lot of framework agnostic packages as well. We extracted Laravels macroable trait to it's own stand alone package because we wanted to add some macroable magic to some of our packages. At the moment of writing the macroable trait is used in our url package and our ssl certificate package. Pretty sure there will be other packages in the future where we will use the trait.

In closing

If you're a package creator and find yourself closing PRs that add methods that you don't deem useful enough to warrant a place in your package, consider adding the macroable trait. Check out the macroable package on GitHub to know more. Also take a look at the Laravel, PHP and JavaScript packages our team previously released. Might be something useful for you in there too.

Who uses PHP (and Laravel) anyway?

Colin DeCarlo, a developer at Vehikl, wrote some thoughts on why PHP has a bad reputation in some circles.
People shitting on PHP isn’t going to go away, it’s a symptom of a few things. PHP has a ridiculously flat learning curve so just about anyone can write code using it, this means a lot of amateurs and ‘get it done’ developers will choose php but won’t really ever level up their skills when it comes to software development. I agree with Colin on everything he writes in his post. I'm also thinking that the some of the reasons on why people don't like PHP apply to Laravel as well. In my mind Laravel is to PHP frameworks what PHP is to other programming languages. Both Laravel and PHP might not do everything by the "real programming rules", but it sure is easy to use. And when handled properly powerful and maintainable stuff can be built with it. Because Laravel is an easy framework to get started with, it's a popular choice for newcomers. Even with almost no experience you can build an app. Some of those projects will go to production. If an experienced developer that uses another framework comes by and sees that Laravel app, it might be easy to conclude that the problem lies with Laravel, and not with the inexperience of the junior programmer who just begon his/her journey in coding.

Extending models in Eloquent

Caleb Porzio, co-presenter of the Twenty Percent Time podcast, published a new article on the Tightenco blog. This time he guides us through a nice use case for extending Eloquent models.
Let’s explore another alternative that can be used as a stand-in for repetitive where statements and local scopes. This technique involves creating new Eloquent models that extend other models. By extending another model, you inherit the full functionality of the parent model, while retaining the ability to add custom methods, scopes, event listeners, etc. This is commonly referred to as “Single Table Inheritance,” but I prefer to just call it “Model Inheritance”.

Build a Facebook Messenger chatbot in Laravel

In a new article on his blog, Christoph Rumpel shows how you can easily set up a Facebook Messenger chatbot using the shiny new v2 of Botman Studio. Very cool stuff.
Although it seems quite easy to setup BotMan Studio and Facebook you still need to be aware of a few concepts regarding Facebook. I hope I could provide them there and this article helps you to setup your next Facebook Messenger chatbots. From here you are ready to build more and more features to your bot your own. So make sure to checkout the BotMan documentation to get a feeling of what is possible and learn new stuff.

The dangers of mutable datetime objects

Jeff Madsen wrote down a good piece that explains how mutable Carbon dates can lead to some nasty bugs. I would't mind if Chronos were to be promoted to the default datetime library in Laravel.
If you hang out on any sort of programming forums you have no doubt encountered “The Great Mutable vs. Immutable Debate”. While I’m sure you know what the words mean, if you are new to programming or don’t have a strong Computer Science background it might not be obvious to you whether this is an important concept to be concerned with, or just more “architecture astronaut” purists arguing some obscure fine point. To help you answer that for yourselves, I’m going to show you the difference between the two using two popular Php DateTime libraries — Carbon and Chronos, and then demonstrate the danger of using the mutable one of those. If you want to read more cool articles by Jeff, be sure to subscribe to his excellent newsletter.

A recap of Laracon EU 2017

Devron Baldwin wrote down a few words on the excellent Laracon EU conference, edition 2017.
The awesome talks and the amazing people made Laracon EU 2017 an experience to remember. I’ll split this up into a few sections to talk about the non-technical and the technical talks. I found myself enjoying the non-technical talks slightly more than the technical this year. I can't believe it' already over and am already looking forward to Laracon EU 2018.

Getting started with laravel-medialibrary: a video tutorial

laravel-medialibrary is probably one of our most powerful packages. It can associate files with Eloquent models. It can also generate derived images such as thumbnails. It has a very developer-friendly API to work with. Here's a quick example:
Want to store some large files on another filesystem? No problem:
$yourModel->addMedia($bigFile)->toMediaCollection('downloads', 's3');
Because the package can do so much, the docs have grown quite large. If you're a visual learner, you'll be happy to know that I've made a video that shows what the medialibrary is capable of.