An Introduction to Single Page Web Applications: Laravel and VueJS

1170 VIEWS

· ·

Over the past few decades, web development has advanced significantly. The speed with which web development has evolved can be credited mainly to internet growth and innovations. In 2020, the internet boasts over 40 billion connected devices, qualifying it as the fastest growing technology; not only in terms of usage, but also in financial returns. With the growth of the internet has come the growth of its corollary: the web application.

A web application is a software tool that runs on a web server and can be accessed by a client web browser over a network such as the internet. Web applications are convenient for use over multiple devices and are easy to update. There are two main types of web applications: Single Page Applications (SPA) and Multiple Page Applications (MPA).

Today, SPAs are more popular than MPAs. They each have pros and cons. The choice of either depends on business objectives, the purpose of the application in question, and further development plans.  

This article will focus on two SPAs used together – Laravel and VueJS – highlighting their strengths as choice web applications by answering the following questions:

  • What is a single page application?
  • What are some single page application Use Cases?
  • Are there pros and cons of single page applications?
  • Why use Laravel and Vuejs for single page applications?
  • How does one set up a basic single page application in Laravel and Vuejs?

What is a Single Page Application?

A Single Page Application (SPA) is a web app or site that interacts with the web browser by dynamically rewriting the current webpage with new data from the server instead of the default method of loading entirely new pages.

The SPA provides a more flexible user experience because it fits in one page and does not need to reload the browser, cutting out the extra waiting time that would have ordinarily been  required to retrieve data.

SPAs are built in JavaScript or JavaScript frameworks, and then compiled to work in the browser, increasing performance. Browsers have become quite powerful today, unlike in the past where every single click triggered a new server request to load a page. Nowadays, SPAs request the markup and data independently, then render the pages straight to the browser. This way, SPAs help in maintaining a constant and outstanding UX in the browser, keeping the user in one comfortable web space while providing them with content in a convenient and simple fashion.

Single Page Applications are mainly developed using advanced JavaScript frameworks such as React, VueJS, AngularJS,Ember.js, Knockout.js andMeteor.js, amongst others.

Some of the most notable SPAs used almost every day include;

  • Gmail
  • Google Maps
  • Facebook
  • Twitter
  • Google Drive
  • GitHub

Why Use SPAs?

Fast and Flexible

SPAs are fast since most resources (HTML + CSSS + Scripts) and DOM components are only loaded once throughout the entire cycle of an application. Subsequently, only dynamic content is loaded by JavaScript, which speeds up the site remarkably.

Simplified Development

The process of developing SPAs is more streamlined and simpler compared to multiple page applications, since one does not need to write a lot of code to render many pages on the server. This encourages code-reuse and is easier for newbie developers.

Easy Debugging

Using JavaScript frameworks and libraries, SPAs are easy to debug and monitor the page elements and data interactions once you inspect element.There are several developer tools on the browser such as webpack, VueJS devtools on Chrome and Firefox.

Flexibility in Developing Mobile Applications

SPAs ensure adaptability when developing both native mobile apps and  web apps since the same backend database and API can be shared. With the components separated, it’s easier to develop a mobile application on the same database because the developer can reuse the same backend code for web application and native mobile application.

Offline App Usage

SPAs offer offline app usage through caching. The application sends only one request, and stores all the cached data on any local storage, which can then be used offline.

When to use a Single Page Application

Single page web applications are mostly used when building dynamic platforms with small data volumes and provide an ideal base for both web and native mobile app development due to their component-based development. Because SPAs rely heavily on SEO optimization, their main drawback is that they rely heavily on JavaScript, thus pages cannot be indexed and there are no unique page keys for search engines to optimize such sites. However, Google has launched a new scheme to enable SPA SEO optimization, but developers must ensure that the JavaScript files can be indexed as Google uses a web crawler to index the dynamic pages.

The other considerations for using SPAs have to do with project and user requirements. For instance, some projects are based on a complex architecture and would prefer multiple-page navigation for further development in the future.

Why use Laravel + VueJS for Single Page Applications ?

Laravel is a popular open-source MVC PHP framework built by Taylor Otwell and supported by a community of developers. It is used to create elegant and full-featured web applications. It supports a variety of features such as authentication, database migrations, Schema builder, blade templating, Object Relational Mapper (ORM), pagination and so on.  

Vue (pronounced /vjuː/, like view) is a progressive framework for building user interfaces.  It is built incrementally from the ground up, and its core library focuses on the view layer thus ensuring easy integration with existing projects and libraries. It is mostly known for its popularity in building single page applications when combined with other modern tools such as Laravel.

Laravel and Vue can be used together to develop excellent event-driven applications whose activity is completely handled on the front-end. Vue uses composable and reactive components, whereby when coupled up with Laravel at the backend, the page content is loaded dynamically by switching contents without reloading the page. This increases the app’s speed and performance without taking up much of a  computer’s resources.

To integrate Vue and Laravel, you create Vue components and use them inside the blade files like you would use regular HTML tags. When the blade file renders, the Vue props are passed to the component as output.

Setting up a Laravel + Vue Single Page Application

To create a Laravel-Vue application, you need to have a Laravel application installed on a web server. In my case, I am using Xampp (on Windows).  Here is how to install a Laravel application.

Prerequisites:

Have a basic knowledge on PHP, MySQL database 

Installation

Please follow the Laravel documentation for installation depending on your operating system.

We will be using composer, a PHP manager dependency. I am going to use the xampp server that comes with the latest version of  PHP, MySQL, and Apache. In case you run into errors during installation, follow the server requirements manual for guidance.

1. Create the project
On your command prompt, navigate to the Xampp’s htdocs folder then type this:

$ composer create-project laravel/laravel myapp

Note that my project name is called myapp, but feel free to use any name.

2. Understand Laravel’s Directory Structure

Laravel uses the MVC architectural pattern where a model, a view and a controller interact with each other to ‘pass’ the message of the application. A model interacts with the database, the controller contains the logic interacting the model, then the view provides the user interface(UI) of the application.

Below is one of the most important and frequently used folders.

 

3. Create a MySQL database

On the phpMyAdmin, create a myapp_db. Take note of your Xampp server’s username and password.On the myapp root folder, open the .env file and change the database name and the localhost credentials.

Generate the application key as shown below:

The .env file will look like this:

APP_NAME=myapp
APP_ENV=local
APP_KEY=base64:0W1r9R6pD1dLm1eoqNWcKKhYJ+B1WN/98bfs5lLCSDc=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=my_app
DB_USERNAME=root
DB_PASSWORD=

4. Run your application

Open the link on the browser to see the default Laravel application.

5. Writing your first Hello world

Navigate to resources, views and welcome.blade.php and change the text to of the blade to this:

<div class="content">
            <div class="title m-b-md">
               First Laravel App
            </div>
            <div class="firstapp">
                <h1>Hello World</h1>
            </div>
 </div>

The final output would then show as:

 

Adding Vue Components to the Laravel Application

At this point, the Laravel application is up and running so we need to integrate it with Vue for the front-end. Since we are developing an SPA, we will only use the welcome.blade.php view that is rendered by the web route inside the routes/web.php file.

Edit the welcome.blade.php view to look like this:

<html>

<head>

   <meta charset="utf-8">

   <meta http-equiv="X-UA-Compatible" content="IE=edge">

   <meta name="viewport" content="width=device-width, initial-scale=1">

   <meta name="csrf-token" content="{{csrf_token()}}">

   <title>SPA</title>

   <link href=" {{ mix('css/app.css') }}" rel="stylesheet">

</head>

<body>

<div id="app">

   <app></app>

</div>

<script src="{{ mix('js/app.js') }}"></script>

</body>

</html>

Inside the #app Div, the app is used to render the Vue.js component, which is responsible for rendering the dynamic page content.

Installing Node

Open the command line, navigate to this folder and run these commands:

$ npm install
$ npm install vue-router

#npm install is used to install the predefined node modules inside the package.json file

#npm install vue-router is used to install the vue-router which used to provide basic Vue Routing for the Vue components.

When the installation is complete, open your resources/assets/js/app.js file and edit the file contents to this:

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import App from './views/App'
import Welcome from './views/Welcome'
const router = new VueRouter({
   mode: 'history',
   routes: [
       {
           path: '/',
           name: 'home',
           component: Welcome
       },
   ],
});
const app = new Vue({
   el: '#app',
   components: { App },
   router,
});

In the above code, we have imported the VueRouter, Vue, and all the Vue component routes that we’ll use in the application. We also defined the routes for the application by instantiating Vue to take all the available components.

The VueRouter constructor takes an array of routes (url and name) as well as the main #app component used as parameters of the route requests.

The next step is to create a couple of Vue file components inside the views folder. Navigate to resources/js then create a views directory inside which you will create two files: Welcome.vue and App.Vue.

Paste the following code inside resources/js/views/Welcome.vue

<template>
   <div class="flex-center position-ref full-height">
       <div class="content">
           <div  class="m-b-md">
               <h2 class="title m-b-md">
                   Hello World
               </h2>
               <h3>
                   Laravel-Vue SPA
               </h3>
           </div>
       </div>
   </div>
</template>
<style scoped>
   .full-height {
       height: 100vh;
   }
   .flex-center {
       align-items: center;
       display: flex;
       justify-content: center;
   }
   .position-ref {
       position: relative;
   }
   .top-right {
       position: absolute;
       right: 10px;
       top: 18px;
   }
   .content {
       text-align: center;
   }
   .title {
       font-size: 60px;
   }
   .links > a {
       color: #636b6f;
       padding: 0 25px;
       font-size: 12px;
       font-weight: 600;
       letter-spacing: .1rem;
       text-decoration: none;
       text-transform: uppercase;
   }
   .m-b-md {
       margin-bottom: 30px;
       color: #000000;
   }
</style>
<script>
   export default {}
</script>

Inside the resources/js/App.vue, paste this code:

<template>
  <div>
 <nav class="navbar navbar-expand-md navbar-light navbar-laravel">
          <div class="container">
              <router-link :to="{name: 'home'}" class="navbar-brand">Home</router-link>
              <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                  <span class="navbar-toggler-icon"></span>
              </button>
              <div class="collapse navbar-collapse" id="navbarSupportedContent">
                  <ul class="navbar-nav mr-auto"></ul>
                  <ul class="navbar-nav ml-auto">
                      <li class="nav-link"> App</li>
                  </ul>
              </div>
          </div>
      </nav>
      <main class="py-4">
          <router-view></router-view>
      </main>
  </div>
</template>
<script>
  export default {}
</script> 

From the above code, you will realize that the App.vue is the parent component that is loaded first and contains several Vue-specific tags such as router-link and router-view.

The router-link is used to generate links for routing to pages defined in our router. The router-view is used to define where all the child component pages will be loaded. In this case, when App.vue is loaded first, when we navigate to home the content inside the Welcome.vue will be loaded inside the router-view, dynamically.

Please note that the script tags inside the two files are empty because we don’t need scripting here.

<script>
  export default {}
</script>

Build the Vue Application

 

$npm run dev

This will compile all the js assets and put them inside the public/js folder.

To run the overall application, we use the usual php artisan command like we’d load a normal Laravel project.

$php artisan serve

When you visit the page, you will see this output screen:

Congratulations, you just built your first-ever Laravel-Vue Single Page Application. The goal of this tutorial was to lay the foundation and show you how easy it is to build a SPA with Vue Router, Vue and Laravel. Consult the Vue Router documentation for further studies.

You can find the project files on GitHub


Faith is a curious software engineer and a data science enthusiast, with a passion for problem-solving through implementation of high-quality software products. She holds a Bachelor’s degree in Computer Science from Ashesi University. She has experience working in academia, fin-tech, healthcare, research, technology, and consultancy industries both in Kenya and Ghana. She combines her passion for teaching, technology and writing to create technical digital content.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published. Required fields are marked *

%d bloggers like this: