Building a Vue SPA with Laravel

Laravel is one of my most preferred PHP frameworks, truth be told it is also one of my preferred frameworks to build Web Applications regardless of programming language. The primary reason for this is that from a framework point of view, it actually takes care of a lot of things for you and it does actually help you to focus on the more important aspects of your application.

Many of the software solutions I tend to get involved in developing these days, the website or what can be termed as the main client interaction point, is usually only the very tip of the application and often what lies behind that is a very complex and tangled web of technological solutions all with varying levels of interactions and dependencies.

These days it is not uncommon to find solutions which ultimately comprise a number of different programming languages and frameworks, so you’ll find PHP, Python, Go, .net core, JavaScript, Java are all utilised throughout the entire software solution landscape. This is primarily due to software teams picking the best language or framework for the job instead of trying to fit the one they know and use to do everything.

One of the aspects I like about Laravel is that in some respects it can be a very opinionated framework yet in others it also actually gets out of the way and enables you to make your own decisions on how you want to use it. Which in my experience is often a very difficult balance for software frameworks to achieve.

One of these areas is where it comes to using your “Frontend Framework” of choice. You can quite literally use any Frontend Framework of your choice with Laravel, it does not necessarily tie you down to any despite the fact that it appears to come prepackaged with Vue.JS. You can equally choose not to have any UI at all and purely use Laravel to develop an API or even Console Application.

Since Laravel version 5.3, Vue.js has been the default frontend framework included in a Laravel installation. There appears to be no official reason why Vue was chosen over other worthy options, such as React, but my guess is that it’s because Vue and Laravel share the same philosophy: simplicity and an emphasis on the developer experience.

Starting a new project with Laravel is easy once you have Laravel installed and configured on your Ubuntu Desktop all it takes is laravel new [project name] however the real art is what to do afterwards

What is Single Page Application

Websites are typically broken up into pages in order to make the information they contain more convenient to consume. This has be traditionally implemented using the server/client model, where each page must be loaded from the server with a different URL. To navigate to a new page, the browser must send a request to the URL of that page. The server will send the data back and the browser can unload the existing page and load the new one. For the average internet connection, this process will likely take a few seconds, during which the user must wait for the new page to load.

By making use of AJAX utilities, a different model is possible: the browser can load an initial web page, but navigating to new pages will not require the browser to unload the page and load a new one. Instead, any data required for new pages can be loaded asynchronously with AJAX. From a user’s perspective, such a website would appear to have pages just like any other, but from a technical perspective, this site really only has one page. Hence the name, Single-Page Application (SPA).

The advantage of the Single-Page Application architecture is that it can create a more seamless experience for the user. Data for new pages must still be retrieved, and will therefore create some small disruption to the user’s flow, but this disruption is minimised since the data retrieval can be done asynchronously and JavaScript can continue to run. Also, since SPA pages usually require less data due to the reuse of some page elements, page loading is quicker.

The disadvantage of the SPA architecture is that it makes the client app bulkier due to the added functionality, so gains from speeding up page changes may be negated by the fact that the user must download a large app on the first page load. Also, handling routes adds complexity to the app as multiple states must be managed, URLs must be handled, and a lot of default browser functionality must be recreated in the app.

Configuring Vue with Laravel

As mentioned previously, Vue for the most part comes pre-packaged with Laravel, so when you create a new project with Laravel and inspect the code you might be think that everything has been preconfigured for you. However, the answer is both a Yes and No!

There is a tremendous amount of time saved here but unfortunately there is still a little bit of work to be done in order to have a fully functioning Vue based frontend. Fortunately, Laravel does come packed with some features to make this really easy to do!

The secret here is that building a Vue single page with Laravel combines building a Clean API driven applications. However, to get them working together we need to esnure that server-side Laravel router is able to work in tandem with the history.pushState API of the Vue Router

The Vue router can be configured to use history mode or the default hash-mode, which uses the URL hash to simulate a full URL so the page won’t reload when the URL changes. Personally, I prefer to use the history mode which means we need to configure a Laravel route to match all possible URLS depending on which route the user enters.

Install Vue-Router in Laravel project

Using a SPA architecture your application will include multiple pages and you’ll need to use a router. A router, in this context, is a library that will mimic browser navigation through JavaScript and various native APIs so that the user gets an experience similar to that of a traditional multi-page app. 

Some frontend frameworks, such as Angular or Ember, include a router library out-of-the-box. The philosophy guiding these frameworks is that the developer is better served with a complete, integrated solution for their SPA. Vue.js, do not include a router. Instead, you must install a separate library.

In the case of Vue.js, an official router library is available called Vue Router. This library has been developed by the Vue.js core team, so it is optimized for usage with Vue.js and makes full use of fundamental Vue features such as components and reactivity.

Using a router in a SPA Application provides the following functionality:

  • Handle navigation actions within a page
  • Match parts of the application to defined routes
  • Manage the address bar
  • Manage browser history
  • Manage Scroll bar behaviour

To get started with this, I am going to assume you have Laravel installed and configured on your Ubuntu Desktop and have already created a new project.

Our first step is to install Vue-Router using yarn. I use PHPStorm so will be running the command using the integrated terminal window in the project root directory

Shell

When vue-router is installed two components have been registered globally throughout your application for use:

  • RouterLink Generally used instead of a tags to create hyperlinks and access Vue Router
  • RouterView Outlet to enable swap of designated page components

Configure Vue-Router in Laravel Project

The Vue-Router maps a route to a component and then renders it with router-view within the context of application

HTML

With Vue Router, different pages of the application are represented by different components. When you set up Vue Router, you will pass in configuration to tell it which URLs map to which component. Then, when a link is clicked in the app, Vue Router will swap the active component so as to match the new URL

We will need to update the resources/assets/js/app.js and configure the Vue router. I typically remove all the existing code and replace it with the below

JS

You may gleen from this that we are going to have to create 2 new Vue components the Home and About views. First,lets introduce a convention, primarily as you may know already Laravel favours convention over configuration which in my view is what software should always attempt to implement. So a convention I try follow when developing Vue applications to try separate out my Views from resuable compoenents.

In this convention a View is typically a component which has a route and a Component is something that can be re-used in multiple routes. So what I like to do is create another folder in resources/js and name is views. In this folder I will create my view components that I have defined in the routes above

We can create these files simply using the terminal window

Shell

Lets now add just enough code to these files in order to get our example working. First lets start with our App.vue file, because this is the outermost container element for our application. We’ll define and application heading and some basic navigation functionality use <router-link/>

HTML

The most important tag in our App component is the <router-view></router-view> tag, which is where our router will render the given component that matches the route (i.e. Home or About).

Next we will add some basic code to the other two views so we have at least have something to display

For the resources/js/views/Home.vue

HTML

For the resources/js/views/About.vue

HTML

We’re now complete with the UI aspect of our application.

Configure Server-side Vue Controller

We are going to leverage the Laravel so that we can build a server-side API interact with our application.

Lets create a new VueController class to ensure that any web route will map to our SPA.

Shell

We will need to ensure the server-side defines a route, to do this we open routes/web.php for editing, to replace the welcome route with the following.

PHP

Open the new Controller to add in the following logic

PHP

We now need to create a new file resources/views/vue.blade.php and add the following code

HTML

The require #app element which contains our App Component has been defined.

Running our Vue SPA

We have now completed all the foundation code for building our SPA application all that is required now is use JavaScript to build and test it out. If like me you are using Homestead to run your application, you will still need to execute this step in order to refresh your machine.

We will use yarn run the watch command

Shell

if we open a browser and visit our test site we will see the following and be able to click on the links and view the pages.

Summary

We have developed a basic skeleton to build a Vue SPA and now we are ready to further build on this and to start using Laravel to develop the API layer which the SPA will interact with.

In order to learn how to further speed up your development process with Laravel you can learn how to include a Material Design Component Framework like MDB Vue Pro to develop great looking web applications using the Material Design Principles developed by Google

Gary Woodfine

Technical Director at Denizon
Gary is Technical Director at Denizon, an independent software vendor specialising in IoT, Field Service and associated managed services,enabling customers to be efficient, productive, secure and scalable in a way which helps them address and reduce their ecological impact.

Denizon's product line successfully integrate IoT, Artificial Intelligence and Blockchain technology to enable efficient, productive, secure and scalable solutions to help organisations address increasing energy demands, ecological impact and Health & Safety concerns of their staff.

Latest posts by Gary Woodfine (see all)