Creating a Laravel-like Auth Mixin in Vue

In Laravel, we have the very useful and convenient auth() helper. When I tried to build my first single-page app while learning Vue.js, this helper was one of the things that I immediately felt was missing and needed to have in my Vue code.

<?php
auth()->id()
auth()->user()
auth()->check()
auth()->guest()

Here I will show you how I replicated Laravel's auth() helper in Vue.js as a global mixin. By the end of this post, we will have these JavaScript equivalents of the previous auth() helper snippet.

this.$_auth.id
this.$_auth.user
this.$_auth.check
this.$_auth.guest

The Vuex Store

The setup that I'm going to use assumes that you use Vuex to handle authentication state. We will also be putting that state in a separate module because it just makes sense to split related chunks of your store into smaller, self-contained pieces.

First, let’s initialize the state.

The user key is all we need here. All of the other properties of the auth mixin will have their values based on this.

// store/modules/auth.js
export default {
state: {
user: null
}
};

Next, we define a getter that returns an object with the properties id, user, check, and guest.

Since I'm focusing mainly on the auth mixin here, I won't be going into how to build a full auth module in Vuex. Just know that you should at least have mutations for setting the user and changing it back to null.