A Laravel package to impersonate users

A great feature of Laravel Spark is it’s ability to impersonate other users. As an admin you can view all screens as if you are logged in as another user. This allows you to easily spot a problem that your user might be reporting. Laravel-impersonate is a package, made by MarceauKa and Thibault Chazottes that can add this behaviour to any Laravel app.

Here are some code examples taken from the readme.

Auth::user()->impersonate($otherUser); // You're now logged as the $otherUser.

Auth::user()->leaveImpersonation(); // You're now logged as your original user.

$manager = app('impersonate');

// Find an user by its ID

// TRUE if your are impersonating an user.

// Impersonate an user. Pass the original user and the user you want to impersonate
$manager->take($from, $to);

// Leave current impersonation

// Get the impersonator ID

It even includes some handy blade directives:

    <a href="{{ route('impersonate', $user->id) }}">Impersonate this user</a>

    <a href="{{ route('impersonate.leave') }}">Leave impersonation</a>

Want to know more, take a look at the package on GitHub.

Laravel’s tap helper function explained

A little known helper function, called tap was added to Laravel 5.3. In this short post I’ll explain how this function can be used.

Let’s first take a look at the tap function itself. It’s actually a very short one.

function tap($value, $callback)

   return $value;

So you give it a $value and a $callback. The $callback will execute with the $value as the argument. And finally the $value will be returned.

Nice, but how is it used in the wild? Let’s take a look at the pull function in Illuminate\Cache\Repository. This function will get the value out of the cache for the specified key and forget it.

This is how it could have been implemented:

public function pull($key, $default = null)
   $value = $this->get($key, $default);

   $this->forget($key) // returns a boolean;

   return $value;

In the example above $this->forget() returns a boolean. So to have our function return the original value, we need to store it in the temporary variable $value first.

This is the actual implementation in Laravel.

public function pull($key, $default = null)
   return tap($this->get($key, $default), function ($value) use ($key) {

In the snippet above there’s no need anymore for a temporary variable. Win! Now, you might argue that it’s less readable. If the arrow functions rfc gets accepted, it can be rewritten as a one liner.

public function pull($key, $default = null)
   return tap($this->get($key, $default), fn($value) => $this->forget($key));

Want to see some more usages of tap? Take a look at the Laravel source code. There’s also a tap method on the Collection class. Read this post on Laravel news to see a few examples.

Environment variables, config caching, and Laravel

In a short blogpost Michael Dyrynda gives some good advice on why you should cache your routes and config values.

As part of the recommended production deploy process it is important to run the caching commands that Laravel affords us via Artisan. This means running config:cache and route:cache, which will compile the config and route files down into a single file each.

In doing so, Laravel aims to speed up parsing of these files by only needing to read a single, rather than multiple files.


Getting started with Varnish Cache

If you want to learn Varnish Thijs Feryn wrote a book for you. It’s free to download until 7th March 2017.

Getting Strated with Varnish Cache is a technical book about the Varnish caching technology. Varnish is a so-called reverse caching proxy that acts as an intermediary between the browser and the webserver. Varnish stores HTTP responses and serves them to the browser, without accessing the backend for every request. This causes a massive speed increase.


Understanding Laravel’s macroable trait

Nicola Malizia wrote a short blog post on how Laravel’s handy Macroable trait can be used and how it works under the hood.

If you check the Laravel codebase I’m sure that you can observe that Laravel makes use of traits.There is one trait in the source code that pulls my attention. I’m talking about the Macroable trait.

The purpose of this trait is to extend (not in an OOP sense) a class at run-time. This way, you can add behavior without editing the original class source code.


Packages that make developing Laravel apps easier

In this post I’d like to share some of the packages that make developing a Laravel app easier.


This package really needs no introduction as it is one of the most popular packages around. It’s made by Barry Vd. Heuvel and it’s a real powerhouse. Once the package is installed it displays a debugbar in your browser that shows a lot of useful info such as the executed queries, which views are used, which controller built up the page, and much much more.



This package, also made by Barry, can generate some files that help an IDE provide improved autocompletion. Using this package PHPStorm can autocomplete methods on facades, classes resolved out of the container and model properties.



Those who are already using Laravel for quite some time know that Laravel 4 provided an artisan command to tail the Laravel default log. Unfortunately in Laravel 5 that command was axed. This package brings it back.

With the package installed you can just run php artisan tail to tail the log.



Laravel 5.3 introduced mailables. A mailable is a class that takes care of everything regarding sending a mail.

One of the things that is not so easy to in a vanilla Laravel app is testing such a mail. In order to for example let your app send an order confirmation mail you have to go through the entire checkout process. The laravel-mailable-test package can make the mailable testing process a lot easier. It provides an artisan command that can send a mailable to a specific mail address.

The package will provide a value for any typehinted argument of the constructor of the mailable. If an argument is a int, string or bool the package will generated a value using Faker. Any argument that typehints an Eloquent model will receive the first record of that model.

If you want to learn more, read this introductory blog post about it.



Made by Mohamed Said, this package can help you test a flow where mail is involved. Instead of sending the actual mail that package will save the mail to the filesystem. In the browser it will display a little notice that a mail was sent. Clicking on the link in that notice will display the saved mail right in your browser.

Here’s a short movie clip that shows how it can be used to test a password reset.



In my projects I have never run a down migration. So I don’t bother with coding up the down steps. And without those down steps running Laravel’s migrate:refresh will result in errors. If you think skipping writing down steps is lazy, read this comment Adam Wathan made on Reddit.

The laravel-migrate-fresh package provides an artisan command that can knock out all your tables without using down steps of a migration.


Do you know some other indispensable package that makes developing a Laravel app easier? Let me know in the comments below.

Polyfills: everything you ever wanted to know, or maybe a bit less

David Gilbertson tells you all about polyfills.

Faced with the reality that you can’t write modern code and expect it to work for all users, you have exactly two choices:

1. Only use language features available in all the browsers you support
2. Write modern code, then do something to make it work in older browsers

If you have decided on option one then I respectfully suggest that you are bonkers, and insist that you state your case in the comments.
I believe that developers who are able to explore all the new stuff and use it in their day-to-day jobs stay happy, and being happy is important.


Moving tech forward with Gomix, Express, and Google Spreadsheets

Matt Stauffer wrote down his experiences with creating a simple app on Gomix, a platform to easily create node powered sites right in your browser.

Gomix is a platform that makes it absurdly easy to spin up a new app (static HTML or Node) and see it online instantly. You can also invite your friends to collaborate, and the moment you make a change in the editor, your site updates. So, at this point I’m using Gomix and Node, and Express is an easy pick.

I strongly considered using Firebase for data storage, but the Gomix team linked me to this Gomix site using Google Spreadsheets as the backing data source and I really wanted to try it out.

So we’ve now settled: I’ll take my old HTML and JavaScript, but instead of the JavaScript loading its data from JSON files, I’ll run an Express app on Gomix pulling the data from Google Spreadsheets and output its data in a JSON format. No big deal.


A package to remember a visitor’s original referer

If you want to know how a visitor got on your site you can check the referer request header. Yeah, it’s misspelled. That header contains the url of the previously visited page. Unfortunately browsers will fill that header regardless of the previous url was an internal or external one. So after the first click on an internal link you won’t know anymore on which site a visitor was on previously.

Our new laravel-referer package aims to fix that problem. Once the package is installed it will remember the original referer in session. So even after a users clicks around on your site, you are still able to detect which site he or she visited previously.

Because users are also often tracked using UTM Codes the package will also remember the utm_source query parameter.

The easiest way to retrieve the referer is by just resolving it out of the container:

use App\Spatie\Referer\Referer;

$referer = app(Referer::class)->get(); // 'google.com'

Or you could opt to use Laravel’s 5.4 fancy new automatic facades:

use Facades\Spatie\Referer\Referer;

$referer = Referer::get(); // 'google.com'

To know more take a look at the readme of the package on GitHub.


Add syntactic sugar by preprocessing PHP

In an awesome article at Sitepoint Christopher Pitt explains how he used the yay macro library to build up plugin framework to add new language features to PHP.

Chris made plugins that allows this syntax in PHP.

// short closure syntax
$items = ["one", "two", "three"];
$ignore = "two";

array_filter($items, ($item) => {
    return $item !== $ignore;
//class accessors

class Sprocket
    private $type {
        get {
            return $this->type;

        set {
            $this->type = $value;

        unset {
            $this->type = "type has been unset";

As with all things, this can be abused. Macros are no exception. This code is definitely not production-ready, though it is conceptually cool.

Please don’t be that person who comments about how bad you think the use of this code would be. I’m not actually recommending you use this code, in this form.

Having said that, perhaps you think it’s a cool idea. Can you think of other language features you’d like PHP to get? Maybe you can use the class accessors repository as an example to get you started. Maybe you want to use the plugin repository to automate things, to the point where you can see if your idea has any teeth.


Check out some more examples on preprocess.io

Very cool stuff.

A package to easily manipulate images in PHP

Today we released a new package called image that makes manipulation images in PHP extremely easy. In this post I’d like to explain why we built it and how it can be used.

Manipulating images in PHP

To manipulate images in PHP there are already a lot of options. You can go hardcore and use the Gd or Imagick functions directly. By using them you get a lot of control, but most of these functions aren’t very developer friendly. If you need something easier to work with try out the Intervention Image library by Oliver Vogel. It provides a nice abstraction and will make working with images a lot easier.

Another option is a package by Jonathan Reinink called Glide. This one is a bit special. Glide can generate images on the fly using url parameters. With Glide installed in your project a cropped version of the image in this bit of html will be automatically generated.

<img src="image.jpg?w=300&h=400&fit=crop" />

Its API is really nice to work with. Under the hood Glide leverages the aforementioned Intervention Image but it hides some of the complex operations behind easy to use parameters. Unfortunately Glide only exposes its API via http, there’s no way to easily programmatorically work with it.

Our image package

Enter spatie/image. Our new package wraps up Glide so all its methods can be used using PHP code.

Basic manipulation

In the remainder of this article we are going to manipulate this beautiful photograph taken in New York City.

Let’s start of with a simple manipulation.


Here’s the result:

Let’s perform crop out that Starbucks storefront.

    ->manualCrop(600, 400, 20, 620)

Check out the documentation to learn which operations the package support.

Converting to other formats

Imagine you want to convert a jpg to a png. Here’s how to do that.


It couldn’t be more simpler, the package will just use the extension of the output file to determine the output format.

Applying changes

By default every manipulation will only be applied once to your image. When calling a manipulation method multiple times only the last call will be applied when the image is saved.

Take a look at this code.


The second call to brightness will override the value set by the first call to brightness. So the resulting image will only have its brightness reduced by 20%.

The apply method will apply all previous manipulations to the image before continuing with the next manipulations.


That code will lower the brightness by 40%, then lower it again by 20%. The result:

Preparing manipulations

In the previous examples all manipulations like brightness and blur were called directly on the Image instance. You could also opt to build up a Manipulations instance.

$manipulations = (new Manipulations())

and then you can use that to manipulate a collection of images.

//using Laravel's collect function

collect($images)->each(function(Image $image) use ($manipulations) {

The manipulate function can also accept a closure.

$image->manipulate(function(Manipulations $manipulations) {

In closing

You’ll find more examples of how you can use spatie/image in the documentation. Right now we’re using Glide behind the scenes to perform the manipulations, but we’ve built up our package in such a way that, in theory, we could swap Glide out for something else, without making any breaking changes.

If you use Laravel and need a good solution to handle images and other files in your app, then check out our laravel-medialibrary package. We’re releasing a new major version soon where all image manipulations are powered by spatie/image.

Also take a look at the PHP and Laravel packages we’ve previously built. Maybe we’ve made something that you can use in your next project.

A link blog to stay in touch with the bigger PHP community

Probably because I’m a heavy user of Laravel I read a lot of Laravel focused blogs and follow a lot people on Twitter who also are heavy users of the framework. But more than a Laravel developer, I consider myself a PHP developer first. One of the ways I try to stay in touch with what is happening in the larger PHP community is following this excellent link blog maintained by Chris Cornutt.


Configuration-driven PHP security advice considered harmful

Scott Arciszewski debunks the commonly given advice on securing your PHP installation by setting some php.ini values.

There have been countless examples posted in various places (Reddit, Hacker News, Twitter, Facebook, Slashdot, and even LinkedIn group discussions), and while a handful occasionally contain one or two tips that might be beneficial towards securing your PHP applications, almost all of the advice they contain is either wrong, a huge waste of time, downright silly, or all of above.

As part of a team that specializes in application security (in particular: securing PHP applications), I feel it’s high time someone cleared the air about this advice.


Why a software patch is called a patch

Bram Van Damme explains the origin of the word “patch” in context of software.

A common misconception is that a software bug is called a bug because of an actual bug – a moth – that got stuck in Harvard University’s Mark II calculator in 1947, and Grace Hopper finding it + taping it inside a logbook.

What seems to be legit however is the history of the term software patch.


Methods Are Affordances, Not Abilities

In a new post on his blog Adam Wathan explains his thinking on the meaning of having a method on an object.

The fundamental misunderstanding here is thinking that methods are things an object can do.

If you believe that the methods on an object represent the abilities of that object, then of course an Announcement having a broadcast() method sounds silly.

But what if methods weren’t the things an object could do? What if they were the things you could do with that object?

If methods were the actions an object afforded us, then it would make perfect sense to be able to broadcast() an Announcement, wouldn’t it?


An artisan command to easily test mailables

Most of the Laravel apps we create at Spatie will send mails. This can be a password reset mail, a welcome mail after registration, an order confirmation mail, … One of the things we do is styling such mails so it has the same look and feel as the site it was sent from. When testing such mails our designers had to request a password reset or go through the entire checkout flow just to receive such an order confirmation mail. To make that testing process a lot easier we’ve created a package called laravel-mailable-test. This package provides an artisan command that can send a mailable to an mail-address.

To send any mailable issue this artisan command:

php artisan mail:send-test "App\Mail\MyMailable" [email protected]

This will send the given mailable to the given email address. The to-, cc- and bcc-addresses that may be set in the given mailable will be cleared. The mail will only be sent to the email address given in the artisan command.

The package will provide a value for any typehinted argument of the constructor of the mailable. If an argument is a int, string or bool the package will generated a value using Faker. Any argument that typehints an Eloquent model will receive the first record of that model.

Image the constructor of your mailable looks like this:

public function __construct(string $title, Order $order) 

That constructor will receive a string generated by the sentence method of Faker and the first Order in your database.

The values that are passed to the constructor of the mailable can be customized using the values option of the command.

php artisan mail:send-test "App\Mail\MyMailable" [email protected] --values="title:My title,order:5"

Using this command My title will be passed to $title and an Order with id 5 will be passed to $order.

To learn more about the package head over to the readme on GitHub. Be sure take also take a look at this list of Laravel packages our team has previously made.

Switching PHP versions with Laravel Valet

Michael Dyrynda, one of the two new hosts of the Laravel Podcast, share a nice tip on how to quickly switch PHP versions when using Laravel Valet.

At the time of writing, Laravel Valet ships with PHP 7.1 but if you’re like me, you have some legacy projects around the place that haven’t quite lifted their dependencies to PHP 7 just yet.

A lot of folks might have previously used a VirtualBox Virtual Machine, or more recently considered Docker but a lot of the time and especially when dealing with simpler situations, Valet may be all that you need.


A checklist for all projects that are going live

Apart from our open source work, we do client work at Spatie as well. Over the years we’ve learned that one of the most critical moments of a project is when it is going live. No matter how you confident you are about the correctness of the code base there are so many big and little things that could go wrong when moving to production.

To make sure a new project is launched correctly we’ve created a list with important items to check off. We’ve shared our checklist on GitHub. Some items are specific to our workflow, bust most things are applicable to any project. There are also tasks on the list that we take care off well before launching but verify again just to make sure that everything is in order. In this post I want to highlight a few items.

  • Use the Chrome DevTools and throttle your CPU and network with 10x CPU slowdown and set the network to “Good 3G”. At our office we use modern Apple hardware and a fast internet connection. Mobile users probably have a much slower internet connection and slower CPU.
  • Check all pages for n+1 problems. Because we use powerful hardware we’re probably not noticing any n+1 problems while developing a project. We use Barry vd. Heuvel’s laravel-debugbar. That awesome package can report all queries that were executed when rendering a page.
  • Add redirects from old to new pages if necessary. Redesign an existing site will often results in a changed site structure. We don’t leave people (and search engines) in the cold and provide redirects from the old urls to the new ones. To manage such redirects in a Laravel app we use our home grown laravel-missing-pages-redirector package.
  • Verify that all http status codes are ok. Links to missing pages are really not classy. That’s why we unleash our crawler on the new site to make sure that links on all pages return a good response code.

The checklist contains many more items. Take a look at the entire list on GitHub: https://github.com/spatie/checklist-going-live

Do you think we’ve missed an important check? Submit a PR.