Using Vue, Vuex, Vue Router with Laravel

Jyoti Duwal
Vue.js Developers
Published in
7 min readNov 23, 2017
Source: http://vue-newsletter.com/vue-newsletter.png

I was about to work on an E-commerce website as my side project and was trying to make it an SPA up to possible extent. So, I decided to use Vue in the front-end and Laravel to handle the back-end.

Before you go further, an intermediate knowledge on both laravel and vue is expected.

Components, Vuex, Vue Router

Components — The parts of a web user interface that form the building blocks for both simple websites and modern front-end applications.

They are one of the most powerful features of Vue or React or any other popular front-end framework and can be defined as small pieces of a software which extend basic HTML element, can be reused and makes the code base more readable. As our project gets bigger, it is obvious to have a number of components. And with higher number of components its likely that we have to manage huge number of props and data our component needs. A time will come when it is really not possible or very hard to maintain the current project.

So, what might be a solution for this?

Vuex?

Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.

Anthony Gore’s blog and Official Doc explains properly when one should consider using vuex. So with that thought in my mind, I decided to use Vuex since I was sure I will have a number of components. I started to search for ways to integrate vuex with laravel in my project. I did not find any straight forward blog post or video which could teach me the thing.

So, inspired from Chris Coyier, for my future reference and for someone who may have the same issue I decided to write a blog post.

A Super Quick Preview!

OK, now lets get our hands dirty with some codes ;).

Setting Up the Back-End

We will first create routes and back-end endpoints from where we will be listing, inserting and updating our notes to database.

Now, lets create a controller where we can hit those requests and can perform relevant operations.

That is all for the back end portion.

Front-End

First, lets pull in all the packages.
We will use the latest stable version of vue, vue-router, vuex and laravel-mix.

Just hit npm -i and npm run watch after running laravel project.

Lets add app.js script to welcome.blade.php

app.js is the entry point of our app. As soon as we hit the index or main root, the view gets called and file gets initiated. We have imported some files for app.js. So lets create them first.

The above api.js was created because we are importing that to our store. A question might arise asking why we wont put that variable over somewhere instead of creating a whole new file for just two lines of codes. Its not necessary in this case since there is a single endpoint but as our project grows up & we have multiple endpoints it would be a good practice to dedicate a separate folder and a file where all api requests stay.

Time to create our first store. Lets name it noteStore.

Lets talk a bit about the above store we just created. A store mainly consists of state, actions, getters and mutations. State consists of the data properties a store may contain. Its lot similar to the data property we have in our components. In our case we have notes and favorite notes. Image from Vuex official documentation pretty much explains the working mechanism of Vuex.

In above noteStore the actions are called or in technical term dispatched by component. Upon being dispatched, it commits respective mutation and the mutation then mutates the store’s data. As we can see the data is mutated only with the mutation and thats the point of using Vuex. While using Vuex only the mutations are supposed to mutate the data.

We will also use Vue-Router for seamless navigation.For that lets create a routes file routes.js where we define the url to hit the specific component.

We referenced an app.js which we included in the welcome.blade.php lets create that now. While we are here lets see how we can use Vue-Router. We can follow the following steps to use Vue-Router

  1. Create a routes.js file and export it
  2. Import the routes in our app.js .
  3. Create a new Vue-Router Instance and pass those imported routes into the instance.
  4. And finally pass that router object to our main vue component.

Since we have created our store, its time we start using it. We just created a vue component and associated it with the element with id of ‘app’, We have then passed the router instance where we have passed the routes object and the store itself. By doing this the noteStore and all its property will be available to the noteApp component and its child component.

Lets now access the store’s data to our component. To fill up some notes we need to create a create component lets name it createNote.vue.

The above note just displays a simple text input box, by hitting enter one can easily create a note. Lets now dive right into the list component, one of our main components.

Lets put a bit of our focus on the script part here.
We are importing mapState from Vuex. Since we had injected store to the main Vue component. We now have access to all the properties of the store. We could access the notes and favrouriteNotes by

this.$store.state.notes

and

this.$store.state.favouriteNotes

respectively. Lets imagine we have 5 more properties and 5 more stores being imported to one of our components. Quickly our code can get repeated here and there and we will be violating the DRY rules. So for our rescue we can use mapState (map the state of the store), by doing

…mapState([‘notes’])

We are pulling in the notes property and can be easily accessible around the whole component and thats reactive at the same time.

We can also map actions simply by doing

...mapActions([
'fetch',
'deleteNote'
]),

in the methods section of our component and call them just by

this.fetch()

But for this project i will dispatch actions right from the store, since we are performing other operations which shall not be done in store.

I will briefly go through how at the moment we are fetching the notes in the list.vue. We can see we are dispatching the fetch action from our component.

this.$store.dispatch('fetch');

now fetch action gets called, what fetch action does is, it hits the back-end api and gets a response. In our action we have access to all the functionality of a store, such as commit, state, dispatch.

fetch({ commit }) {
return axios.get(notes)
.then(response => commit('FETCH', response.data))
.catch();
},

It then commits a mutation and sends the fetched response.Finally our mutation then mutates the data property, and the change is reflected wheresoever we have made use of it.

state.notes = notes;

The same goes for favouriteList component.

Wrapping Up

While naming the mutation in uppercase is not mandatory, its considered to be a good practice to do so since it distinguishes itself from a normal function.

Since i didn't want to make it super long, i have taken a quick approach rather than a good one. Some of the things i believe will make it even better are.

  1. Creating different files for mutation, state and action.
  2. Making the whole project even more modular like creating a note folder inside of note and putting all the related Vue and store files inside of it.By doing so we can then change the noteStore to store.js.

Some more features to be added.

  1. Pagination
  2. Syncing Data between tabs.
  3. Handling errors

Since this is my first time using Vuex please pour in any suggestions in case you have to make this even better.

Second Part (where we look how we can use it in a modular pattern.)

These blog posts State Management in Vue and Learn Vuex by Building a Notes App , official doc helped me a lot while i was writing all this.

I would love to take a bit of time to thank my colleagues Saroj Shahi making my blog more readable and constantly encouraging me to write my very first blog post. Also would love to thank Amrit Gc, Samundrak, Sajan Rajbhandari, sabin chalise, Ujjwal Ojha, Madhu Sudhan Subedi, Pranin Shakya, Anish Duwal for giving me suggestions at times and technically helping me whenever i had any issue.

And a big dose of thanks goes to everyone reading this.

Here is the Github repo for the source code.

Happy Coding.. :)

--

--