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.
https://vessel.shippingdocker.com

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;

StripeWebhookCall::find($id)->process();

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' => [
        App\Listeners\ChargeSource::class,
    ],
];
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: https://images.guide/
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
https://quickadminpanel.com/blog/stripe-payments-in-laravel-the-ultimate-guide/

Partitioning for concurrency in synchronous business processes

On his blog Frank De Jonge, member of the PHP League and creator of Flysystem, explains a cool pragmatic solution how to ensure queued processes for the same user complete in the right order.
The use of multiple workers allows for much higher throughput, but it also allows for race conditions during processing. When messages for the same user are sent to different workers, handling order can no longer be guaranteed. Therefore we have failed to fulfil our business rule. If we were able to ensure every message from the same user were sent to the same worker, the worker could ensure those messages are handled in order while the system as a whole would still benefit from the degree of parallelism. But how do we make this happen?
https://blog.frankdejonge.nl/parallelise-synchronous-business-processes/

BetterReflection v2 has been released

The awesome Roave team has recently released v2 of their BetterReflection package. It can do anything PHP's native reflection API can, but without actually autoloading the code.
The operational concept is quite simple, really: 1. We scan your codebase for files matching the one containing your class. This is fully configurable, but by default we use some ugly autoloader hacks to find the file without wasting disk I/O. 2. We feed your PHP file to PHP-Parser 3. We analyse the produced AST and wrap it in a matching Roave\BetterReflection\Reflection\* class instance, ready for you to consume it.
Read all about it on Marco Pivetta's blog: https://ocramius.github.io/blog/roave-better-reflection-v2.0/

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.

Browsershot

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:
Browsershot::url('https://spatie.be')->bodyHtml();
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.

laravel-medialibrary

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
$yourModel
   ->getMedia()
   ->first()
   ->getTemporaryUrl(Carbon::now()->addMinutes(5), 'thumb'); // Temporary S3 url

laravel-translatable

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.

laravel-demo-mode

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.
https://jason.pureconcepts.net/2017/09/nexmo-sms-admin-laravel/

Goodbye controllers, hello request handlers

Jens Segers, developer at Teamleader and author of the popular Optimus and laravel-mongodb packages, wrote about an alternative to controllers.
Let me introduce you to request handlers. The concept is very simple, yet very unknown to a lot of PHP developers. A request handler is basically a controller, but limited to one single action. This concept is very similar to the Action-Domain-Responder pattern which was proposed by Paul M. Jones, an alternative for the MVC pattern that focuses on a more clear request to response flow for web applications.
https://jenssegers.com/85/goodbye-controllers-hello-request-handlers

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->mixin($mixin);

$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.
https://medium.com/@colindecarlo/who-uses-php-anyway-672115ab81de 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”.
https://tighten.co/blog/extending-models-in-eloquent

PHP 7.2 is due in November. What’s new?

PHP 7.2 is just around the corner. In new blogpost Martin Hujer walks us through the changes.
PHP 7.2 is planned to be released on 30th November 2017 (see the timetable). And it comes with two new security features in the core, several smaller improvements and some language legacy clean-ups. In the article, I will describe what the improvements and changes are. I read the RFCs, discussions on internals and PRs on Github, so you don't have to.
https://blog.martinhujer.cz/php-7-2-is-due-in-november-whats-new/

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.
http://christoph-rumpel.com/2017/09/build-a-facebook-chatbot-with-laravel-and-botman-studio/