Using destructuring assignment in for VueJS loops

Ivan Sieder offers a nice tip on how to write better v-for loops in VueJS component templates.

There is really nothing wrong with the above code, but there is a small aspect, which really bugs me. As you can see, we are repeating the product identifier inside the output twice ({{ product.name }} and {{ product.price }}).

We are modern web developers (at least I hope so) and therefore we are going to use modern ES6 functionality. The feature we are going to use is called destructuring assignment. Basically, what the destructuring assignment allows us to do, is to pull a specific property off of an object and store it in a variable.

https://simedia.tech/blog/vue-js-destructuring-assignment-for-loops/

TypeScript With Laravel Mix

In a new post on his blog Sebastian De Deyne, multi disciplinary wizard at Spatie, explains how to set up TypeScript in a typical Laravel app.

In a recent Spatie project we decided to give TypeScript a shot for the business critical part of a new application. TypeScript provides static analysis to reduce the chance of introducing bugs, to have self-documenting code, and to improve our tooling (autocompletion!)

Adding TypeScript support is pretty straight forward and is done in three steps: install the necessary dependencies, configure TypeScript, and finally configure Laravel Mix.

https://sebastiandedeyne.com/posts/2017/typescript-with-laravel-mix

DHH’s opening keynote at RailsConf 2017

Like at most previous editions, DHH delivered a keynote at RailsConf 2017. This year he spoke on the importance of belong to a group, programmer values, and belief systems. I love being in the Laravel community, but one thing that annoys me sometimes is the “us” vs “them” mentality you feel here and there. What I find great about DHH’s talk is that is a positive approach to the values of Ruby community. He doesn’t say that the other communities are bad, or lesser then them.

Anyways, go watch this keynote, it’s great.

The case for singleton objects, façades, and helper functions

Matthias Noback explains the value of singleton objects: we properly used they can make your code more developer friendly.

I’m not advocating the use of façades and helper functions per se. I assume they may have good use in specific parts of your application (just as the Laravel documentation states, by the way). My point is that, as long as you build into your libraries both options, you can offer a great developer experience, providing an out-of-the-box working solution of a useful service, which can still be used in a project that uses dependency injection everywhere.

https://php-and-symfony.matthiasnoback.nl/2017/05/the-case-for-singleton-objects-facades-and-helper-functions/

A package to enable short class names in an Artisan tinker session

Tinker is probably one of my most used Artisan commands. A minor annoyance is that it can be quite bothersome having to type the fully qualified classname to do something simple.

Today we release a new package called laravel-tinker-tools. When fully installed let’s you use the short class names in a tinker session:

This magic does not only work with models but with every class in your Laravel app.

Installing the package

There are a few non standard steps you need to take in order to install the package.

First, pull in the package like you normally would:

composer require spatie/laravel-tinker-tools

Next, create a file named .psysh.php in the root of your Laravel app with this content:

<?php

\Spatie\TinkerTools\ShortClassNames::register();

Finally, dump the optimized version of the autoloader so autoload_classmap.php gets created.

composer dump-autoload -o

And with that all out of the way you can use short class names in your tinker session.

A peek behind the curtains

When you use a class that hasn’t been loaded in yet, PHP will call the registered autoloader functions. Such autoloader functions are responsible for loading up the requested class. In a typical project Composer will register an autoloader function that can include the file where the class is stored in.

Composer has a few ways to locate the right files. In most cases it will convert the fully qualified class name to a path. For example, when using a class App\Models\NewsItem Composer will load the file in app/Models/NewsItem.php. It’s a bit more complicated behind the scenes but that’s the gist of it. To make the process of finding a class fast, Composer caches all the fully qualified classnames and their paths in the generated autoload_classmap.php, which can be found in vendor/composer.

Now, to make this package work, \Spatie\TinkerTools\ShortClassNames will read Composer’s autoload_classmap.php and convert the fully qualified class names to short class names. The result is a collection that’s being kept in the $classes property

Our class will also register an autoloader. When you use NewsItem in your code. PHP will first call Composer’s autoloader. But of course that autoloader can’t find the class. So the autoloader from this package comes next. Our autoloader will use the aforementioned $classes collection to find to fully qualified class name. It will then use class_alias to alias NewsItem to App\Models\NewsItem.

What happens if there are multiple classes with same name?

Now you might wonder what’ll happen it there are more classes with the same name in different namespaces? E.g. App\Models\NewsItem, Vendor\PackageName\NewsItem. Well, autoload_classmap.php is sorted alphabetically on the fully qualified namespace. So App\Models\NewsItem will be used and not Vendor\PackageName\NewsItem.

Because App starts with an “A” there’s a high chance that, in case of a collision, a class inside your application will get picked. Currently there are no ways to alter this. I’d accept PRs that make this behaviour customizable.

Need more tinker magic?

There are a lot of other options that can be set in tinker.config.php. Learn all the options by reading the official psysh configuration documentation. Caleb Porzio‘s excellent blogpost “Supercharge Your Laravel Tinker Workflow” is an excellent read as well. This package was inspired by that blogpost

Maybe you don’t need tinker…

If you want to run a single line of code tinker can be a bit of overkill. You must start up tinker, type the code, press enter, and quit tinker. Our laravel-artisan-dd package contains an Artisan command that can dump anything from the commandline. No need to start and quit tinker anymore.

We’ve updated the package so you can make use of short class names too. Here’s how you can dump a model using a minimal amount of keystrokes:

In closing

laravel-tinker-tools and laravel-artisan-dd aren’t the only packages we’ve made that make developing Laravel apps easier.

Be sure to take a look at these ones at well:

Need even more stuff? The open source section on our company website lists everything we’ve released previously:
https://spatie.be/en/opensource

Videos of the talks at Laravel Nigeria’s first meetup

On April 22nd Laravel Nigeria held its first meetup. It was a big success with over 150 developers showing up.

Here’s a recap written by Neo Ighodaro, the organiser of the meetup:
https://blog.devcenter.co/building-the-laravel-nigeria-community-with-over-150-attending-the-first-meetup-c919d5ca373c

The talks of the meetup were recorded, you can watch them here:

Testing a Vue component part 5: Jest awesomeness and a skeleton to get started

Welcome to part 5 of a series on how to test a Vue component.

Here’s the table of contents of the series:

  1. Starting out with tests
  2. The first test and snapshot testing
  3. Creating an instance of a component
  4. More tests and faking time
  5. Jest awesomeness and a skeleton to get started (you’re here)

Jest watch mode

You know by now that Jest is an amazing testing tools that comes with jsdom and snapshot testing built in. But a thing we haven’t touched upon is it’s test runner. Typing jest on the command line will make it run all the tests but it can do much more. It has an awesome interactive mode that you can start by jest --watch.

When Jest is in this mode it will run the tests when one of the files in your project changes. You can also press enter to manually trigger a test run. A very cool feature is that you can put a filter on which tests to run by pressing t (or p).

Now when a file changes only the tests containing storage in their name will run. I really wish all test runners (I’m looking at you PHPUnit) had this built in.

Our skeleton repository

Like already mentioned getting started with testing a Vue component was a pain because you need to have a good environment set up. To avoid going to through the same pain again I created a skeleton repo to kickstart Vue component development. Sebastian played a big role is setting all this up just right. This repo is what I’ll be using myself when working on the next component.

Here’s how you can get started with it:

  1. Clone the repo [email protected]:spatie/skeleton-vue.git
  2. Run rm -rf .git && git init to cut loose the connection to our repo on GitHub
  3. Run yarn to pull in the dependencies.
  4. Replace all occurrences of the string mentioned at the top of the readme.

The skeleton already contains an ExampleComponent and a test to make sure that component is working. If you run ./node_modules/.bin/jest you’ll see that test is passing.

In closing

Congratulations, you’ve reached the end of this series. I hope you liked learning all this stuff and that reading all of this make you want to start creating and testing a Vue component of your own. Although starting with testing may be daunting, try to persist and eventually you will be rewarded with progress and results. If you feel like you’re stuck ask a colleague or a programming friend for some help.

Testing a Vue component part 4: more testing and faking time

Welcome to part 4 of a series on how to test a Vue component.

Here’s the table of contents of the series:

  1. Starting out with tests
  2. The first test and snapshot testing
  3. Creating an instance of a component
  4. More tests and faking time (you’re here)
  5. Jest awesomeness and a skeleton to get started
    More tests and faking time

More tests

If you navigate to http://vue-tabs-component.spatie.be/#second-tab you’ll notice that the tab named Second tab is automatically opened. Let’s take a look at the test that makes sure this functionality works.

it('uses the fragment of the url to determine which tab to open', async () => {
    window.location.hash = '#second-tab';

    await createVm();

    expect(document.body.innerHTML).toMatchSnapshot();
});

Let’s go through it in detail. First we set the hash of the current window.location (that’s JavaScript speak for the current url) to #second-tab. Remember, Jest comes with jsdom out of the box. It’s jsdom that provides us with that window instance.

Next we create a new Vue instance and await until Vue has done it’s thing. Finally we assert that the rendered output matches the saved snapshot. Of course I’ve manually verified, when that snapshot was first created, that it’s content was correct.

Asserting against a component property

Instead of using snapshots to make assertion you can also just assert against a property in the state of a Vue component. Let’s see how that works.

Our vue-tabs-component has a neat feature where you can make a tab use a custom fragment. Here’s the relevant test.

it('uses a custom fragment', async () => {
    document.body.innerHTML = `
        <div id="app">
            <tabs cache-lifetime="10">
                <tab id="my-fragment" name="First tab" >
                    First tab content
                </tab>
            </tabs>
        </div>
    `;

    const tabs = await createVm();

    expect(tabs.activeTabHash).toEqual('#my-fragment');
});

First we set up some html and we await until Vue has done it’s thing. Like mentioned before the createVm method return an instance of the Tabs component. We implemented our component in such a way that the activeTabHash-property in it’ state always contains the hash of the tab that’s being displayed. In that last line of the test we simply assert that the property contains the expected value.

Faking time

By default our tabs component will remember which was the last open tab. If you for instance navigate to http://vue-tabs-component.spatie.be/#second-tab and then to the same url without the fragment you’ll notice that the Second tab is being displayed.

The component remembers, for a limited amount of time, the last opened tab by writing the hash of the selected tab to local storage. Here’s the code that does that:

expiringStorage.set(this.storageKey, selectedTab.hash, this.cacheLifetime);

That expiringStorage class is something custom that is included in the project. It’s a wrapper around local storage. It makes items in local storage expiring.

expiringStorage has it’s own tests. Let’s take a look one of those tests.

it('remembers values by key', async () => {
    expiringStorage.set('my-key', 'my-value', 5);

    expect(expiringStorage.get('my-key')).toEqual('my-value');
});

Pretty simple right? We store my-value in the storage using the key my-key and then we assert that we get the same value when getting my-key. That last parameter is the lifetime in minutes.

Of course we should not only test that the value is being saved, but that is expires after five minutes.

Here’s the test for that:

it('returns null if the value has expired ', () => {
    expiringStorage.set('my-key', 'my-value', 5);

    progressTime(5);

    expect(expiringStorage.get('my-key')).toEqual('my-value');

    progressTime(1);

    expect(expiringStorage.get('my-key')).toBeNull();
});

We assert that after exactly 5 minutes we still get the right value. If time progresses any further the value is forgotten and null is returned.

That progressTime() function is not part of Jest. It’s coded up in the tests themselves. Let’s go take a look at it’s implementation.

function progressTime(minutes) {

    const currentTime = (new Date()).getTime();

    const newTime = new Date(currentTime + (minutes * 60000));

    const originalDateClass = Date;

    Date = function (dateString) {
        return new originalDateClass(dateString || newTime.toISOString());
    };
}

We’ll go over this line by line. In JavaScript a way of getting the time is the built-in Date class.

const currentTime = (new Date()).getTime();

We calculate the new time by adding the right amount of milliseconds to it.

const newTime = new Date(currentTime + (minutes * 60000));

Here comes the tricky part. We here going to hold a reference to the original date class. And then we are going to replace the built-in Date with our own function.

const originalDateClass = Date;

Date = function (dateString) {
    return new originalDateClass(dateString || newTime.toISOString());
};

This is called monkey patching. The original Date is replace by a function that, given no parameters, it won’t return the actual time, but the time we gave it (newTime). Cool! Btw you can’t do it this in PHP, which is a shame because it would make testing stuff a lot easier.

Now that you understand how progressTime works let take a look at these two tests from inside tabs.test.js.

it('opens up the tabname found in storage', async () => {
    expiringStorage.set('vue-tabs-component.cache.blank', '#third-tab', 5);

    const tabs = await createVm();

    expect(tabs.activeTabHash).toEqual('#third-tab');
});

it('will not use the tab in storage if it has expired', async () => {
    expiringStorage.set('vue-tabs-component.cache.blank', '#third-tab', 5);

    progressTime(6);

    const tabs = await createVm();

    expect(tabs.activeTabHash).toEqual('#first-tab');
});

In the first test we set a value in the expiring storage with a key we know our component will use. Then we let Vue do it’s thing. When it’s ready we assert that the right tab is active.

In the second test we set the same value in the expiring storage, but then we are going to progress time. Finally we assert that the item in expiringStorage is not being used, but that the first tab is being used.

Now you might think that the that last test is a bit unnecessary. To so degree you’re right: with the test of the expiringStorage class itself we already covered the items do in fact expire. But that extra extra component test gives me some extra confidence that the component behaves correctly.


You’ve reached the end of part four. Only one more part to go: Jest awesomeness and skeleton to get started

Testing a Vue component part 3: Creating an instance

Welcome to part 3 of a series on how to test a Vue component.

Here’s the table of contents of the series:

  1. Starting out with tests
  2. The first test and snapshot testing
  3. Creating an instance of a component (you’re here)
  4. More tests and faking time
  5. Jest awesomeness and a skeleton to get started

Creating an instance of the Vue component

Now you know what snapshot testing is, let’s take a fresh look at that first test:

it('can mount tabs', async () => {
    await createVm();

    expect(document.body.innerHTML).toMatchSnapshot();
});

The component itself is created in the createVm() function. We’ll explain that await thingie a bit later. Let’s take a look at createVm first. You can find it’s implementation at the end of the file.

async function createVm() {
    const vm = new Vue({
        el: '#app',
    });

    await Vue.nextTick();

    return vm.$children[0];
}

Here we actually create a Vue instance. It will operate on the #app node. Remember we set the dom to some html earlier in the test. Vue will go do it’s business and replace tabs and tab tags by the templates inside the Tabs and Tab components. It will not do this immediately but in an asynchronous way. We need to wait until Vue is ready. That’s what that Vue.nextTick() line is all about. This will resolve after Vue’s done with it’s rendering work and all it’s magic.

If you read the documentation regarding nextTick you’ll learn it returns a promise when you don’t pass it any parameters. So you can use then() on it. If you’re not familiar with promises, read this article about them.

Vue.nextTick().then(function() {
  //do stuff when Vue is ready
});

The problem if we were to use it that way is that only inside the callback we would know that Vue has done it’s job.

Luckily there is a new JavaScript feature that we can make use of: async/await. In short it lets you write asynchronous code in a synchronous way. Instead of having to pass a function to then when can put the await keyword before Vue.nextTick(). The code underneath that line will only execute when Vue.nextTick() is done.

await Vue.nextTick();

//do stuff when Vue is ready

Cool, so now we lose one level of indentation. You might think: “Freek, this is madness, now the code is blocking”. But rest assured that behind the curtains JavaScript will still use promises and run asynchronously. Async/await is just syntactic sugar. You should also know that any function that uses await should be marked as async. That’s why you see async appear in createVm()s function declaration.

If you want to know more about async/await read this article on PonyFoo or this one on Hackernoon.

This is the last line of the createVm function:

return vm.$children[0];

This line returns the first child of the Vue instance, which is the initialized Tabs component.

Back to the first test

Let’s take a a third and final look at the our first test.

it('can mount tabs', async () => {
    await createVm();

    expect(document.body.innerHTML).toMatchSnapshot();
});

Now you should understand more or less everything that is going on. First we create a new Vue instance that will operate on the dom we set in the beforeEach each method. With that await keyword we will wait (in an asynchronous way) until Vue has done it’s business. And finally we assert that the html matches the content of the snapshot.

Congratulations for reading until here. I hope you learned a lot by diving into that first test. I promise that with this new knowledge the rest of the test are now easier to understand.


Understanding that first test was hard, but now you’ve taken that hurdle, grasping the next tests will be easier. If you’re eager to know more head over to the fourth part of this series: More tests and faking time.

Testing a Vue component part 2: the first test and snapshots

Welcome to part 2 of a series on how to test a Vue component.

Here’s the table of contents of the series:

  1. Starting out with tests
  2. The first test and snapshot testing (you’re here)
  3. Creating an instance of a component
  4. More tests and faking time
  5. Jest awesomeness and a skeleton to get started

Setting up the world

Let’s take a further look at tabs.test.js. Near the top of the file you can see this line

beforeEach(() => {

The function that is passed to beforeEach will be run before each test. It’s used to set up the ‘world’ you’re testing in. It’s equivalent to setUp method of PHPUnit if you’re familiar with that.

Let’s take a look what’s inside beforeEach. That first thing that’s happening there is this:

document.body.innerHTML = `
    <div id="app">
        <tabs>
            <tab name="First tab">
                First tab content
            </tab>
            <tab name="Second tab">
                Second tab content
            </tab>
            <tab name="Third tab">
                Third tab content
            </tab>
        </tabs>
    </div>
`;

Here we see one of Jest’s cool features. It comes with jsdom built in. Jsdom simulates an entire DOM as if you were in a browser. In that code snippet before we’re making sure that each test starts out with that piece of html in the dom.

The first test

Before reviewing the rest of beforeEach, let’s take a look at the very first test. The purpose of this test is to assert that when the component is mounted the right html is being used. “Mounted” is Vue speak for “when the component has fully started up and has been rendered”.

it('can mount tabs', async () => {
    await createVm();

    expect(document.body.innerHTML).toMatchSnapshot();
});

Even though it’s just a few lines there are a lot of things going on, and I can imagine it’s a bit confusing if you’re not familiar with modern Javascript. Let’s go through it in detail.

What happens here is that we first are creating an instance of our component (more on that later) and then assert that the html being displayed, so the value of document.body.innerHTML, is correct. That expect method is part of Jest itself. Jest contains various methods to assert things such as toEqual, toBeNull and much more. On this page in the Jest documentation you can see all available assertion methods.

Instead of asserting the contents of document.body.innerHTML against a big piece of html, we use toMatchSnapshot here. Let’s find out what that method does.

Snapshot testing

The basic idea of snapshot testing is that you compare the output of your code against a file that’s written on disk. That file is called a snapshot. If the output of your test matches up with the contents of that snapshot, it succeeds, otherwise, it fails. It’s a simple as that.

In our project the test are stored in the __tests__/__snapshots__ directory. If you open up tabs.test.js.snap you’ll see the html that is used in the can mount tabs tests.

The cool thing is that you don’t need to write those snapshots by hand. Jest can generate them for us. If you delete tabs.test.js.snap file and run the test again you might think that the can mount tabs will fail, but you’re wrong. Let’s see what happens. You can run the test separetly with this command

jest -t="can mount tabs"

You can see in the output of the command that there was one snapshot generated. The tabs.test.js.snap has been created. You could now verify in that snapshot if the content is equal to the output you were expecting. Run the test again and you’ll see that it’ll pass.

Let’s try and make the test fail. We’re going to cheat a little here and mimick changed output by just editing the current snapshot (in real life you would never edit the snapshot manually). If I changed the html in the snapshot a bit and run the test again, it fails.

If you want to know more about snapshot testing you can read this article my colleague Seb wrote about it, watch this video on how I used snapshot testing in PHP or just go over the relevant page in the Jest documentation.


We’ve learned some good things about that first test. But there’s more. The story continues in part 3 of the series: Creating an instance of a component

Testing a Vue component part 1: getting started

Recently we released vue-tabs-component, a simple Vue component to render a tabular interface. If you want to know more about to the component itself I suggest you head to the introductory post on it. Like with the vast majority of our open source work this package comes with tests. In this series of blogposts I’d like to delve a little bit deeper in those tests.

We’ll touch upon Jest, jsdom, snapshot testing, async/await, monkey patching and a whole lot more. I hope you’re ready for the ride.

Here’s the table of contents of the series:

  1. Starting out with tests (you’re here)
  2. The first test and snapshot testing
  3. Creating an instance of a component
  4. More tests and faking time
  5. Jest awesomeness and a skeleton to get started

Starting out with tests

I’m not ashamed to say that starting out with writing tests for a Vue component was very daunting at first.

The only thing I knew was that I wanted to use Jest, a modern testing platform for JavaScript, because I had used it before and was quite happy with it. More on Jest later.

Sure, the official Vue docs explain how to do simple assertions But for a real life component that documentations doesn’t cut it. The tests of our component should assert that it is rendered correctly in the dom, that is caches that name of the last opened tab](https://github.com/spatie/vue-tabs-component), that it opens the right tab when navigating to a url with a specific fragment, that the fragments can customized and much more.

Luckily my colleague Sebastian helped a lot with setting up the right environment to write the tests in. If you want to write and test your own Vue component check out our skeleton-vue repo that contains all the right things to get started.

With this solid setup I could move past the initial frustration and write some tests.

A first look at the tests

If you want to follow along with you should clone the vue-tabs-component repo with

git clone [email protected]:spatie/vue-tabs-component

Inside the cloned repo, run yarn (or npm install) to pull in all dependencies. Because it is listed in our package.json file that command will also pull in jest, our test runner. To run all the tests for the package issue this command ./node_modules/.bin/jest. You could opt to alias that to jest .

You’ll see this output.

All tests are green, great!

You might wonder where those tests are stored an how Jest finds them. Well, the tests themselves are stored in the __tests__ directory. You’re not required to name that directory as such, but it seems the convention that most Jest users are following. Jest will just scan your entire project for files that end on test.js and execute the tests inside them.

Let’s take a look at our first real test. Open up __tests__/expiringStorageTest.js. This file contains all test that make sure our Vue component is working correctly.

Near the top of the file you see this line:

describe('vue-tabs-component', () => {

That describe function is part of Jest. The first parameter is just the name of your test suite (it is displayed when you run Jest). The second parameter is a function that contains the tests you want to run. Inside that function you’ll see lines starting with the it function such as:

it('can mount tabs', async () => {
it('displays the first tab by default', async () => {
...

Those it functions contain the actual tests. The second argument of it is function that is the test itself, the first argument is the name of that test. Notice that together with the it before it, the name of the test clearly says what is going to be tested: it can mount tabs. You haven’t seen those labels in the output when running Jest before because there are multiple test files in our project. You can run all the test from a single file by just passing that file as a second argument of Jest.

jest __tests__/tabs.test.js

That’ll output something this:


Our journey into the wicked world of Vue component testing continues in the second part of this series: The first test and snapshot testing.

A Vue component to display tabs

Last week my company released a vue-tabs-component, a quality Vue component to easily display tabs. You can view a demo of the component here. In this post I’d like to tell you all about it.

Why we created it

If you’re just want to know what the component does, skip to the next section.

Nearly all projects we deliver are powered by Blender, our Laravel application template. Blender has an admin section where users can manage content. For every content type it provides a crud interface. Nothing special there. But sometimes those content type can be pretty complex and have many many fields. Instead of displaying all the fields at once we put fields that belong in their own tap. So their might be a tab “Content” with some general fields, a tab “Media” with everything regarding images and uploads, … This tab behaviour is provided by some custom JavaScript.

Currently the JavaScript used in Blender is a bit of a patchwork. Because we nowadays use quite a bit of Vue in client projects we decided to make Vue a first class citizen in the admin section as well. We’re currently searching an building Vue components to use in Blender. The tabs component is the first one that we finished building. Though it’s a bit opinionated towards our use case, the component was generic enough to open source.

Introducing vue-tabs-component

If haven’t already done so, head over to the demo page to get a feel of what the component can do.

If you can registered the component globally like this:

//in your app.js or similar file
import Vue from 'vue';
import {Tabs, Tab} from 'vue-tabs-component';

Vue.component('tabs', Tabs);
Vue.component('tab', Tab);

you can use this piece of html to render the tabs like they are displayed on the demo page.

<tabs>
    <tab name="First tab">
        This is the content of the first tab
    </tab>
    <tab name="Second tab">
        This is the content of the second tab
    </tab>
    <tab id="oh-hi-mark" name="Custom fragment">
        The fragment that is appended to the url can be customised
    </tab>
    <tab prefix="<span class='glyphicon glyphicon-star'></span> " 
         name="Prefix and suffix" 
         suffix=" <span class='badge'>4</span>">
        A prefix and a suffix can be added
    </tab>
</tabs>

Easy right?

The component doesn’t come with any styling. If you like the pretty looks of our the demo, you can snatch the css used on GitHub.

Some nice features

The component will use the fragment of the url to choose which tab to open. So clicking navigating to https://example.com#second-tab will display the contents of the tab named Second tab.

The component will also remember which tab was opened previously. If you reload without fragment the tab that is currently active will receive focus again. You’ll find more about this feature on Github.

The rendered output of the component adheres to the ARIA specification. Aria stand for “Accessible Rich Internet Applications” and describes which attributes html nodes should have in order to make the component accessible to people with disabilities

Testing the component

If you look at the source code of the projects you’ll notice that has a test suite to make sure it works properly. Want to know more about how those tests are set up? Then head over the dedicated series of posts on those tests.

In closing

Head over the repo on GitHub to learn more about the component. Though our focus in open source is more creating on Laravel and PHP framework agnostic stuff, take a look at these other JavaScript packages we’ve previously made.

The List Function & Practical Uses of Array Destructuring in PHP

Sebastian De Deyne wrote a cool blogpost on array destructuring in PHP. Yet another reason to stay up to date with the latest and greatest PHP version.

PHP 7.1 introduced a new syntax for the list() function. I’ve never really seen too much list() calls in the wild, but it enables you to write some pretty neat stuff.

This post is a primer of list() and it’s PHP 7.1 short notation, and an overview of some use cases I’ve been applying them to.

https://sebastiandedeyne.com/posts/2017/the-list-function-and-practical-uses-of-array-destructuring-in-php

Comparing vue.js datatable components

Stefan Moises compares a few popular Vue datatable components.

To “get into” Vue.js, I am going to compare different “datatable” solutions I came across and which I found promising. In the past, working with jQuery and mainly AngularJS (1 and 2) and also JAVA frameworks like Grails it was always very difficult and cumbersome to find a really good datatable, which was easy to use, stable and had all the features the projects needed.

http://www.rent-a-hero.de/wp/wp-content/uploads/2017/04/vuegrid

Quickly dd anything from the commandline

Laravel’s tinker command allows to run any code you want as if you are inside your Laravel app. But if you want to run a single line of code if can be a bit bothersome. You must start up tinker, type the code, press enter, and quit tinker.

Our new spatie/laravel-artisan-dd package contains an Artisan command to dd anything from the commandline. No need to start and quit tinker anymore.

Here’s a simple example of how you can use it:

You can dd anything you want. Of course the output will be pretty printed. Here’s an example where an Eloquent model is dumped.

Multiple pieces of code can be dumped in one go:

php artisan dd "bcrypt('secret')" "bcrypt('another-secret')"; 

The dd artisan command using PHP’s eval to run arbitrary code. Be aware that this can be potentially dangerous. By default the command will only run in a local environment. You can make it run in other environments by setting an ALLOW_DD_COMMAND enviroment variable to true.

If you like this package go check it out on GitHub. This isn’t the first package our team has made. Go check out this big list of Laravel packages on our company website to learn if we’ve made anything that could be of use to you.

A tool for making JavaScript code run faster

Even though I’don’t like Facebook as a user, their amazing contributions to open source are something to be very grateful for. Last week they presented their new work in progress: Prepack.

Prepack is a tool that optimizes JavaScript source code: Computations that can be done at compile-time instead of run-time get eliminated. Prepack replaces the global code of a JavaScript bundle with equivalent code that is a simple sequence of assignments. This gets rid of most intermediate computations and object allocations.

https://prepack.io/

It’s still in development, so best not use it in production environments yet.

Expressive Code & Real Time Facades

In a new post on his blog Taylor Otwell gives a nice example on how real time facades can make code more testable.

Recently, I worked on some code that surfaced my most common use-case for Laravel 5.4’s “real-time” facades. If you’re not familiar with this feature, it allows you to use any of your application’s classes as a Laravel “facade” on-demand by prefixingFacades to the namespace when importing the class. This is not a feature that is littered throughout my code, but I find it occasionally provides a clean, testable approach to writing expressive object APIs.

https:[email protected]/expressive-code-real-time-facades-41c442914291